19

I have the following mongoose schema structure

userSchema = new Schema({
    roles: [
        role: {type: Schema.Types.ObjectId, ref: 'Role' }
    ]
})

rolesSchema = new Schema({
  name: String,
  roleEntities: [
    {
      entity : {type: Schema.Types.ObjectId, ref: 'RoleEntity' },
      abilities : [{type: Schema.Types.ObjectId, ref: 'Ability' }]
    }
  ]
}

roleEntitiesSchema = new Schema({
  name: String
})

abilitiesSchema = new Schema({
  name: String
})

How can i populate all these nested documents while doing a find on the USER model?

I tried using populate as below

User.find(ctx.request.query).populate(
      {path: 'roles.role'
      ,populate: { path: 'roleEntities.entity'}
    }).
    exec()

but it's not resolving roleEntities.entity

chridam
  • 100,957
  • 23
  • 236
  • 235
jozzy
  • 2,863
  • 3
  • 15
  • 12

4 Answers4

21

Here's an extreme example of a deep populate nested inside of multiple objects/arrays:

Deal.find()
    .populate({
      path: 'fund',
      populate: [{
        path: 'organizer',
        populate: {
          path: 'banking.accounts.transactions.associatedInvestment',
          model: 'Investment'
        }
      }, {
        path: 'documents'
      }]
    })
K. Waite
  • 1,574
  • 13
  • 12
19

You can try chaining populate operations

User.find()
.populate("roles.role")
.populate("roles.role.roleEntities.entity")
14

Mongoose 4 :

User
  .find()
  .populate({
    path: 'roleIds',
    model: 'roles',
    populate: {
      path: 'otherIds',
      model: 'other'
    }
  })
Rayjax
  • 7,494
  • 11
  • 56
  • 82
6

for me worked the following

  .populate({
            path: 'favorites.favorite',
            model: 'Joke',
            populate: {
              path: 'user',
              model: 'User',
            },
Sorin Veștemean
  • 1,772
  • 19
  • 17