How to populate nested entities in mongoose?

三世轮回 提交于 2021-02-15 11:03:36

问题


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


回答1:


You can try chaining populate operations

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



回答2:


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'
      }]
    })



回答3:


Mongoose 4 :

User
  .find()
  .populate({
    path: 'roleIds',
    model: 'roles',
    populate: {
      path: 'otherIds',
      model: 'other'
    }
  })



回答4:


for me worked the following

  .populate({
            path: 'favorites.favorite',
            model: 'Joke',
            populate: {
              path: 'user',
              model: 'User',
            },


来源:https://stackoverflow.com/questions/36996384/how-to-populate-nested-entities-in-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!