【发布时间】: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