【问题标题】:Mongoose query returns error, but error is the result I am looking forMongoose 查询返回错误,但错误是我要查找的结果
【发布时间】:2019-02-24 04:05:15
【问题描述】:

在 Mongoose 中,当我调用以下代码时:

db.Person.find({}).then((err, author) => {
   if (err) {
     console.log("err",err);
   } else {
    console.log('author', author);
    }
  });

它返回一个错误,而不是我正在寻找的文档,并且该错误似乎是我正在寻找的文档。见这里:

为什么它会返回错误而不是实际对象?我试图从返回的文档中访问属性。该对象存在于我的数据库中:

【问题讨论】:

  • 我更正了我的答案,你的 .then 是落后的

标签: javascript node.js mongodb express mongoose


【解决方案1】:

根据文档:https://mongoosejs.com/docs/promises.html 您应该使用 query.exec() 来获得完整的承诺:

// `.exec()` gives you a fully-fledged promise
var promise = query.exec();

promise.then(function (doc) {
  // use doc
});

当你像承诺一样使用它时,

.then((doc)=>console.log(doc))

doc 是实际的文档,最终会出现错误

.catch(err=>console.log(err))

【讨论】:

    【解决方案2】:

    当您使用 .then() 并且 promise 已解决时,您将在 then() 中获得结果。

    .then((result) => console.log(result))
    

    当 promise 被拒绝时,您可以在以下位置捕获错误:

    .catch((error) => console.log(error))
    

    Promise 分为三个阶段 resolverejectpending

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-04
      • 2013-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-24
      • 2014-02-20
      相关资源
      最近更新 更多