-1

Suppose I have two schemas on MongoDB:

const personSchema = Schema({
  _id: Schema.Types.ObjectId,
  name: String,
  email: String,
  things: [{ type: Schema.Types.ObjectId, ref: 'Thing' }]
});

const thingSchema = Schema({
 _id: Schema.Types.ObjectId,
  title: String,
  fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});

Every time a user logs in, I would like to show the things that they have posted, as well as the fans that are following each of the things. I am able to use populate and select to get to that:

    const user = await personModel
      .findOne({ _id: req.user._id })
      .populate({
        path: "things",
        select: ["title", "fans"]
        }),

However, I am only getting the id of each fan, and not the fan's name and email. I can't quite figure out how to use populate to reference the person collection again.

The outcome I am trying to achieve is that:

  • the user object would have an array of things
  • the thing object would have an array of fans
  • the fan object would have two values - name and email of the fan
jessl
  • 1
  • 1

1 Answers1

1

You can do nested population with:

const user = await personModel
  .findOne({ _id: req.user._id })
  .populate({
    path: 'things',
    select: ['title', 'fans'],
    populate: { path: 'fans' },
  })
  .exec();
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29
  • Oh gosh, this works! It took me so long and now I'm finally seeing that the key is to nest populate in the outer populate object! – jessl Sep 19 '22 at 14:30