2015-05-26 63 views
2

使用猫鼬,我想在我的主文档的子文档中填充属性。 这里是我的模型:猫鼬+在子文档中填充属性

var device = { 
    deviceId: {type: String, required: true}, 
    number: {type: Number, default: 0} 
}; 

var notification = new Schema({ 
    createdAt: {type: Date, default: Date.now}, 
    device: {type: Schema.ObjectId, ref: 'Device'} 
}); 

var clientSchema = new Schema({ 
    [...] 
    information: { 
     code: {type: String, required: true}, 
     name: {type: String, required: true} 
    }, 
    notifications: [notification], 
    [...] 
}); 

我试图做到这一点是得到与填充设备的通知。

我尝试这样做:

clientModel.findOne({"information.code": id}) 
     .populate('notifications') 
     .populate('notifications.device') 
     .exec(function(err, client) { 
      if (err) { 
       console.log(err); 
       next(err, null); 
      } 
      if (client) { 
       console.log(client.notifications); 
       next(null, client.notifications); 
      } 
     }); 

而且我得到了这个

[{ device: 55634975d20f1f3903ff4325, 
    _id: 5564b1139ac484db0251b4a2, 
    createdAt: Tue May 26 2015 19:44:51 GMT+0200 (CEST) }] 

任何人都可以告诉我,我做错了什么?请 感谢您的帮助:)

+0

[Mongoose:deep population(populate populated field)](http://stackoverflow.com/questions/18867628/mongoose-deep-population-populate-a-populated-field) – laggingreflex

回答

0

在您的clientSchema通知是一个嵌入,所以你不需要填充它。尝试删除查询中的填充('通知')。你应该只需要填充('notifications.device')。

0

正确的方法来填充是:

clientModel.findOne({"information.code": id}) 
     .populate('notifications.device') 
     .exec(function(err, client) { 
      if (err) { 
       console.log(err); 
       next(err, null); 
      } 
      if (client) { 
       console.log(client.notifications); 
       next(null, client.notifications); 
      } 
     }); 

注意的是,使用.populate( '通知')的是不必要的,因为通知引用嵌入式。这条线可能导致问题。