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

使用Mongoose的findOne方法检查Express路由参数中customListName是否存在

问题分析与解决方案

你的代码存在两个核心问题:

  • Mongoose Promise版findOne的回调参数逻辑错误:then的第一个参数是查询成功的结果,错误需通过.catch()捕获,而非放在then的回调里。
  • 打印字符串与需求不符,且代码缺少闭合括号,存在语法问题。

修正后的代码如下:

List.findOne({ name: customListName })
  .then(function(foundList) {
    if (!foundList) {
      console.log("not exit"); // 不存在时打印
    } else {
      console.log("exists"); // 存在时打印
    }
  })
  .catch(function(err) {
    console.error("查询出错:", err); // 捕获查询过程中的错误
  });

关键说明:

  1. Promise回调逻辑修正:findOne成功执行时,then的回调接收查询到的foundList;若查询过程中出现错误(如数据库连接问题),会进入.catch()处理。
  2. 打印内容调整:直接替换为你期望的"exists"和"not exit"。
  3. 语法补全:补全了原代码缺失的}),确保代码可正常执行。

如果习惯用async/await语法,代码会更简洁直观:

async function checkListExists() {
  try {
    const foundList = await List.findOne({ name: customListName });
    if (!foundList) {
      console.log("not exit");
    } else {
      console.log("exists");
    }
  } catch (err) {
    console.error("查询出错:", err);
  }
}

// 在路由处理函数中调用
checkListExists();

内容的提问来源于stack exchange,提问作者Mohd Arbaz Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 13:42:20