1

Using Mongodb, mongoose, nodejs, express....

I have a structure like this...

const EventSchema = new mongoose.Schema({
  eventDate: {
    type: Date
  },
  attendees: [
    {
      type: mongoose.Schema.ObjectId,
      ref: 'Person'
    }
  ],
  staff: [
    {
      person: {
        type: mongoose.Schema.ObjectId,
        ref: 'User'
      },
      department: {
        type: String,
        enum: ['photography', 'data-entry', 'mgmt', 'other']
      }
    }
  ]
});

I know how to populate('attendees department'). That works fine and returns ALL data for both. But, because I'm dealing essentially with multiple populates, how do I SELECT the SPECIFIC fields that should be retrieved for attendees and department?

WebDevGuy2
  • 1,159
  • 1
  • 19
  • 40

1 Answers1

3

You can write your query as following, to populate multiple values & return only specific fields that you require

Event.find().populate([{
    path: 'attendees',
    model: 'Person',
    select: '_id name profile_pic' //Fields you want to return in this populate
}, {
    path: 'staff.person',
    model: 'User',
    select: '_id name profile_pic' //Fields you want to return in this populate
}])
Sarfraaz
  • 1,273
  • 4
  • 15