Mongoose +填充子文档中的属性

时间:2015-05-26 18:31:36

标签: node.js mongodb mongoose mongoose-populate

使用mongoose,我想在我的主文档的子文档中填充一个属性。 这是我的模特:

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

任何人都可以告诉我,我做错了吗? 谢谢你们的帮助:)

2 个答案:

答案 0 :(得分:0)

在您的clientSchema通知中是嵌入式的,因此您无需填充它。尝试删除查询中的填充(“通知”)。你应该只需要填充('notifications.device')。

答案 1 :(得分: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(' notifications')的使用是不必要的,因为通知 引用嵌入。这条线可能导致问题。

相关问题