2017-03-29 69 views
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(...) 

回答

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)); 
       }) 
      } 
     }) 
    } 
}) 

您需要像上面那樣填寫每個子文檔。