【问题标题】:ModeMongoose's Async/Await with Mongoose Deep Populate ChainModeMongoose 的 Async/Await 与 Mongoose Deep Populate Chain
【发布时间】:2018-06-30 00:39:26
【问题描述】:

在使用 async/await 时,让链式 mongoose 命令按顺序运行时遇到了很多麻烦。一个简单的await Model.find({}) 命令可以在异步函数中按预期工作,但是当我使用lean、populate 和exec 链接查找命令以用于深度填充(http://mongoosejs.com/docs/populate.html#deep-populate)时,我无法按我喜欢的顺序运行它们。

const messageSchema = new Schema({
  ...
})
const Message = mongoose.model("message", messageSchema)

const chatSchema = new Schema({
  conversations: [{
      messages: [{ type: Schema.Types.ObjectId, ref: "message" }]
  }]
})
const Chat = mongoose.model("chat", phoneSchema)

console.log("11111111111")

const chat = await Chat.findOne({ ... })
  .lean()
  .populate({ path: "conversations" })
  .exec(async (err, docs) => {
    const options = {
      path: "conversations.messages",
      model: "message",
    }

    const result = await Chat.populate(docs, options,
      (e, foundChat) => foundChat)

    console.log("22222222222")

    return result
  })

console.log("333333333333")

结果:

11111111
33333333
22222222

期望的结果:

111111111
222222222
333333333

【问题讨论】:

    标签: node.js mongodb asynchronous mongoose mongoose-populate


    【解决方案1】:

    不知道为什么,尝试了很多不同的方法,但都有效。

    const chat = await Chat.findOne({ ... })
      .populate({
        path: "conversations.messages",
        model: "message",
      })
      .exec((error, foundChat) => foundChat)
    

    【讨论】:

      【解决方案2】:

      我觉得你的代码有两个问题:

      1. 在使用了 lean() 选项后,您无法调用 populate()。 Lean() 将返回的对象转换为常规的 javascript 对象,而不是 猫鼬文档。 Populate 是 mongoose 的内置方法,所以只能在 mongoose 文档中使用。这与您的问题无关,但重要的是要知道。

      2. 当您在查询上调用 exec() 并将回调作为参数传递时,它不会返回承诺,因此“等待”子句对其无效。这就是为什么您的函数不等待 Chat.findOne() 解决并直接转到最后一个 console.log 的原因。以下可能会起作用:

        const chat = await Chat.findOne({ ... })
         .populate({ path: "conversations" })
         .exec().then(async (docs) => {
           const options = {
             path: "conversations.messages",
             model: "message",
           }
        
           const result = await Chat.populate(docs, options)
        
           console.log("22222222222")
        
           return result
        })
        

      【讨论】:

        猜你喜欢
        • 2018-07-06
        • 2016-04-19
        • 2018-03-29
        • 2019-04-15
        • 1970-01-01
        • 1970-01-01
        • 2020-08-03
        • 2018-10-18
        • 1970-01-01
        相关资源
        最近更新 更多