You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node+Express+MongoDB查询无匹配时跳转错误页的实现问题

解决方案

核心逻辑是在数据库查询完成后,判断返回的结果集是否为空,再决定渲染对应页面:

  1. 判断查询结果长度
    在查询回调或Promise的then方法中,检查返回的图书数组长度。如果长度为0,渲染自定义的noResults页面;否则渲染原有的queryResult页面。

  2. 修改后的代码示例
    假设你的查询路由是POST请求,修改后的代码如下:

    app.post('/search', (req, res) => {
      const query = req.body.searchQuery;
      // 使用Promise风格查询(推荐)
      Book.find({ title: new RegExp(query, 'i') })
        .then(books => {
          if (books.length === 0) {
            // 传递查询词到无结果页面,方便提示用户
            res.render('noResults', { query });
          } else {
            res.render('queryResult', { books });
          }
        })
        .catch(err => {
          console.error('查询出错:', err);
          res.status(500).send('服务器查询失败');
        });
    });
    

    如果习惯使用回调风格,逻辑一致:

    app.post('/search', (req, res) => {
      const query = req.body.searchQuery;
      Book.find({ title: new RegExp(query, 'i') }, (err, books) => {
        if (err) {
          console.error('查询出错:', err);
          return res.status(500).send('服务器查询失败');
        }
        if (books.length === 0) {
          res.render('noResults', { query });
        } else {
          res.render('queryResult', { books });
        }
      });
    });
    
  3. 配套视图准备
    确保在EJS的views目录下创建noResults.ejs文件,示例内容:

    <!DOCTYPE html>
    <html>
    <head>
      <title>无查询结果</title>
    </head>
    <body>
      <h2>抱歉,没有找到与 "<%= query %>" 相关的图书</h2>
      <a href="/">返回首页重新查询</a>
    </body>
    </html>
    
  4. GET请求场景适配
    如果是GET方式的查询,只需将app.post改为app.get,并从req.query获取参数:

    app.get('/search', (req, res) => {
      const query = req.query.searchQuery;
      Book.find({ title: new RegExp(query, 'i') })
        .then(books => {
          if (books.length === 0) {
            res.render('noResults', { query });
          } else {
            res.render('queryResult', { books });
          }
        })
        .catch(err => {
          console.error('查询出错:', err);
          res.status(500).send('服务器查询失败');
        });
    });
    

内容的提问来源于stack exchange,提问作者Sirfara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 23:31:09