我想在Mongoose中使用populate
方法来查询集合。这是我的架构:
var UnitSchema = new Schema({
name: {
type: String,
required: true
},
unitNumber: Number,
members: [MemberSchema],
orgs: [OrgSchema]
});
var MemberSchema = new mongoose.Schema({
name: {
first: String,
last: String
},
phone: String,
email: String
});
var OrgSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
sortIndex: Number,
roles: [RoleSchema]
});
var RoleSchema = new mongoose.Schema({
name: String,
sortIndex: Number,
member: {
type: Schema.Types.ObjectId,
ref: 'Member'
}
});
以下是一个示例Unit
集合:
{
"_id": "58da7bd6e7092e8735646ba0",
"name": "Unit Name",
"orgs": [
{
"name": "Org name",
"sortIndex": 0,
"_id": "58da7bd6e7092e8735646c2d",
"roles": [
{
"name": "Role Name",
"sortIndex": 0,
"member": "58dbd1e6c9a893a7840472ad"
}
]
}
],
"members": [
{
"name": {
"first": "First Name",
"last": "Last Name"
},
"_id": "58dbd1e6c9a893a7840472ad"
}
]
}
如何将Member
doc填充到Roles
集合中的成员字段,以便我的输出如下:
[
{
"name": "Org name",
"sortIndex": 0,
"_id": "58da7bd6e7092e8735646c2d",
"roles": [
{
"name": "Role Name",
"sortIndex": 0,
"member": {
"name": {
"first": "First Name",
"last": "Last Name"
},
"_id": "58dbd1e6c9a893a7840472ad"
}
}
]
}
]
这是我想到的查询:
Unit.findOne({unitNumber: unitNumber}).populate('roles.callings.member').exec(...)
答案 0 :(得分:1)
你走了!
unit.findOne({unitNumber: 543})
.populate('orgs')
.exec(function(err, unitDoc){
var subDoc = unitDoc.orgs;
for(var org of subDoc){
org.populate('roles', function(err, data){
var rolesDoc = data.roles;
for(var role of rolesDoc){
role.populate('member', function(err, rdata){
console.log(JSON.stringify(unitDoc));
})
}
})
}
})
您需要填写每个子文档,如上所述。