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

Model.findOne()不再接受回调函数,寻求下述代码的修复方案

解决 Model.findOne() 不接受回调的问题

问题原因

新版本 Mongoose 已废弃回调式调用,Model.findOne() 不再支持传入回调函数,必须改用 Promise 或 async/await 语法。

解决方法

提供两种常用改写方式:

方式1:使用 Promise 的 then/catch

app.get("/", function(req, res) {
  Item.findOne({})
    .then(foundItems => {
      if (!foundItems) { // findOne返回单个文档,不能用length判断是否存在
        return Item.insertMany(defaultItems);
      } else {
        res.render("list", {listTitle: "Today", newListItems: foundItems});
      }
    })
    .then(() => {
      console.log("Successfully saved default items to DB.");
      res.redirect("/");
    })
    .catch(err => {
      console.log(err);
    });
});

方式2:使用 async/await(更简洁易读)

app.get("/", async function(req, res) {
  try {
    const foundItems = await Item.findOne({});
    if (!foundItems) {
      await Item.insertMany(defaultItems);
      console.log("Successfully saved default items to DB.");
      res.redirect("/");
    } else {
      res.render("list", {listTitle: "Today", newListItems: foundItems});
    }
  } catch (err) {
    console.log(err);
  }
});

额外注意点

  • 原代码中 foundItems.length === 0 的判断逻辑错误:findOne() 返回单个文档对象而非数组,需用 !foundItems 判断是否查询到结果。
  • insertMany 同样不再支持回调,需同步改用 Promise 或 async/await 写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:33:15