简体   繁体   中英

Mongoose how to update subdocument field?

This is my 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);

I am trying to push data into the notification.notidata.data by the following way and it seems to not be working.

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

It seems like I am not getting how to access that sub-documented field called data.

Try the $set as:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM