0

I have a two mongoose schema with the following structure.

const ImageSchema = mongoose.Schema({
      image: {
        type: Schema.Types.ObjectId,
        ref: 'Media',
        default: null,
      },
      caption: {
        type: String,
        trim: true,
        default: ''
      },
      credit: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        default: null,
      }
})

const NewsStorySchema = mongoose.Schema({
  ...,
  images: [ImageSchema]
  ...,
})

In one of the my api endpoints I have used mongoose aggregation. In it, I have successfully used $lookup stage to populate other foreign fields in NewsStory model. But I am unable to figure out how to populate the each image and credit inside images since it is an objectId inside an object, inside an array. Actual data looks something like this.

{
  images: [
    {
      image: "507f191e810c19729de860ea",
      caption: "A Rainny Day",
      credit: "707f191e810c19729de860eb"
    },

    {
      image: "607f191e810c19729de860ea",
      caption: "Sweet Delight",
      credit: "827f191e810c19729de860ns"
    }
  ]
}

How may I populate the image and credit using the $lookup stage.

1 Answer 1

1

I think the magic word to your problem whould be $unwind.

it should look likely like this:

{ '$unwind': '$images' },
{ '$lookup':
        { 
            from: 'Media',
            localField: 'images._id',
            foreignField: '_id',
            as: 'images.image' } },
{ '$unwind': '$images' },
{ '$lookup':
        { 
            from: 'User',
            localField: 'images._id',
            foreignField: '_id',
            as: 'images.user' } },

And then you have to group your data.

How to use it is very good explained in this issue:

Mongoose.aggregate(pipeline) link multiple collections using $unwind, $lookup, $group

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.