【问题标题】:Mongoose how to update subdocument field?Mongoose如何更新子文档字段?
【发布时间】:2019-02-26 17:10:29
【问题描述】:

这是我的架构

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

似乎我不知道如何访问称为数据的子记录字段。

【问题讨论】:

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


    【解决方案1】:

    试试$set:

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

    【讨论】:

    • 您是否尝试过更新的答案?只是位置运算符需要在notidata 之后移动,因为那个是实际的数组
    猜你喜欢
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 2018-10-09
    • 2014-11-15
    • 1970-01-01
    • 2017-03-17
    • 2021-12-23
    相关资源
    最近更新 更多