0
我想在Mongoose中使用populate
方法來查詢一個集合。這裏是我的架構:如何使用Mongoose從兄弟收集中填充字段?
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
文檔的成員字段的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(...)