How to populate nested entities in mongoose?

jozzy picture jozzy · May 3, 2016 · Viewed 11.4k times · Source

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

Answer

aec picture aec · May 3, 2016

You can try chaining populate operations

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