猫鼬如何更新子文档字段?

时间:2018-09-22 15:31:35

标签: node.js mongodb mongoose mongodb-query mongoose-schema

这是我的模式

var UserSchema = new Schema({

    username: String,
    email: String,
    password: String,
    company: String,
    contact: Number,
    country: String,
    isLoggedIn: Boolean,
    createdOn: { type: Date, default: Date.now },
    ads: [{ type: Schema.Types.ObjectId, ref: 'Ad' }],
    notification: {
        counter: {type: Number, default: 0},
        notidata: [{ itemdate: { type: Date, default: Date.now }, data: {type: String}}]
    }

});


var User = module.exports = mongoose.model('User', UserSchema);

我正尝试通过以下方式将数据推送到notification.notidata.data中,但似乎无法正常工作。

User.findByIdAndUpdate(newuser.id, {
  '$set': {
    'notification.$.counter': '1',
    'notification.$.notidata.data': 'two updated'
  }
}, function(err, post) {

  if (err) {
    console.log(err)
  } else {
    console.log(post);
  }
});

似乎我没有获得如何访问该子文档字段data的信息。

1 个答案:

答案 0 :(得分:1)

尝试将$set设置为:

  '$set': {
    'notification.counter': '1',
    'notification.notidata.0.data': 'two updated'
  }
相关问题