【问题标题】:Mongoose + Populate a property in a subdocumentMongoose + 在子文档中填充属性
【发布时间】:2015-08-08 13:56:26
【问题描述】:

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

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

谁能告诉我我做错了什么?? 谢谢你们的帮助:)

【问题讨论】:

标签: node.js mongodb mongoose mongoose-populate


【解决方案1】:

正确的填充方式是:

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') 是不必要的,因为 notification 引用嵌入式。这条线可能会导致问题。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-08-16
      • 2017-01-27
      • 1970-01-01
      • 2014-08-16
      • 1970-01-01
      • 2020-12-18
      • 2017-03-21
      • 2017-06-06
      • 2016-01-07
      相关资源
      最近更新 更多