问题
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