Node.js Mongoose如何更新子文档字段?
这是我的模式Node.js Mongoose如何更新子文档字段?,node.js,mongodb,mongoose,mongodb-query,mongoose-schema,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: [{
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的子文档字段。尝试
$set
如下:
'$set': {
'notification.counter': '1',
'notification.notidata.0.data': 'two updated'
}
你试过更新答案了吗?只需将位置操作符移动到notidata之后,因为该操作符是实际数组