Home > OS >  How to populate nested fields in schema mongodb
How to populate nested fields in schema mongodb

Time:12-29

I have a summary schema with a structure like this

  {
    sender: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    summary: {
      type: String,
    },
    sent: {
      type: Date,
      default: Date.now,
    },
  }
);

then a convo schema: NOTE: summary in this schema is an array of objectId, convo returns an array of objects after fetching, sender is in each of the objects gotten after populating the summary field

{
    lastMessage: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "messages",
    },
    members: {
      type: [mongoose.Schema.Types.ObjectId],
      ref: "User",
      required: true,
    },
    summary: {
      type: [mongoose.Schema.Types.ObjectId],
      ref: "summary",
    },
    gigDetails: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Gig",
    },
  }

I want to populate the sender field in the summary array in the convo schema when fetching it, in addition to the already populated summary field. How can I do this?

CodePudding user response:

You can do it like this:

ConvoModel.find(filter).populate([{ path: 'summary', populate: { path: 'sender' } }])

CodePudding user response:

// Fetch the convo documents
const convos = await Convo.find()
  .populate("summary")
  .exec();

// Iterate through the convos array
for (let i = 0; i < convos.length; i  ) {
  // Iterate through the summary array and populate the sender field in each element
  const summaryPromises = convos[i].summary.map(async summary => {
    return await summary.populate('sender').execPopulate();
  });

  // Wait for all promises to resolve
  await Promise.all(summaryPromises);
}
  • Related