Search code examples
node.jsmongodbasynchronousmongoosemongoose-populate

ModeMongoose's Async/Await with Mongoose Deep Populate Chain


I'm having a lot of trouble getting the chained mongoose commands run in sequential order when using async/await. A simple await Model.find({}) command works as one might expect in an asynchronous function, but when I chain find commands with lean, populate, and exec for the purposes of deep population (http://mongoosejs.com/docs/populate.html#deep-populate) I am not able to run them in order as I'd like.

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")

Result:

11111111
33333333
22222222

Desired Result:

111111111
222222222
333333333

Solution

  • Not sure why, tried a lot of different things, but this works.

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