Home > database >  populate all array of objects
populate all array of objects

Time:04-19

I have a schema of concerts which I am populating with reviews using virtual populate which returns an array of reviews. Now on every review I again have to populate customerId to its name and avatar.

Here is my code

const populateReviews = await Concert.findById(id).populate({
    path: "reviews",
    options: {
      sort: { rating: -1, updatedAt: -1 },
    },
  });
const populateCustomers = await Customer.populate(populateReviews, {
  path: "reviews.customerId",
  options: {
    select: { name: 1, avatar: 1 },
  },
});

And here is the output of above code.

enter image description here

I have to populate customerId. Please help me with this.

CodePudding user response:

Populating across multiple levels would help you

Concert
 .findById(id)
 .populate({
    path: "reviews",
    options: {
      sort: { rating: -1, updatedAt: -1 },
      },
    populate : {
    path : 'customerId',
    options: {
       select: { name: 1, avatar: 1 },
      },
     }
  })
 .exec(function (err, res) {

 })
  • Related