skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER
    // 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);
    }
    

  2. You can do it like this:

    ConvoModel.find(filter).populate([{ path: 'summary', populate: { path: 'sender' } }])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search