How to populate nested entities in mongoose?
Asked Answered
N

4

20

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

Navigable answered 3/5, 2016 at 5:37 Comment(0)
C
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'
      }]
    })
Cadmar answered 10/10, 2018 at 22:1 Comment(0)
B
19

You can try chaining populate operations

User.find()
.populate("roles.role")
.populate("roles.role.roleEntities.entity")
Brazee answered 3/5, 2016 at 6:19 Comment(0)
R
14

Mongoose 4 :

User
  .find()
  .populate({
    path: 'roleIds',
    model: 'roles',
    populate: {
      path: 'otherIds',
      model: 'other'
    }
  })
Rainie answered 22/10, 2017 at 10:16 Comment(0)
A
6

for me worked the following

  .populate({
            path: 'favorites.favorite',
            model: 'Joke',
            populate: {
              path: 'user',
              model: 'User',
            },
Adjudicate answered 7/9, 2020 at 6:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.