简体   繁体   中英

How to use populate, within select, in MongoDB?

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM