我有一个文档,该文档具有不在架构中的数组属性。当我尝试通过推送元素来更新此属性时,文档在我的节点应用程序中得到更新:我可以看到对象已修改了数组,但是当文档保存时,数组将保持原样,并且其他属性也会更新。阅读代码时,您会很好理解。
User.findOne({email: req.user.email})
.then(user=>{
if(user.get("posts")){
let posts = user.get("posts");
posts.push("word");
user.set("posts", posts);
//the problem is here
//`posts` is reassigned properly to `posts` with pushed value but it can't be saved with this changement.
}else{
//this is when the "posts" property doesn't exist in document so it just gets added well=>no problem
user.set("posts", "word")
}
//if you have `user.set("a","b")` the document gets this field added and `posts` doesn't get updated
//if the document has property "c" set to "d" and you have `user.set("c", "h")` the "c" property gets updated properly
user.save();
res.send(user);
//you can see here that the object has been successfully updated but in mongodb you cannot see the `posts`updated
})
.catch(err=>{
if(err)throw err;
});
这是架构
const UserSchema = new Schema({
_id: {type: ObjectId, auto: true},
username: {type: String, required: true, max:18},
email: {type: String, required: true},
password: {type: String, required: true, min:5},
date_of_registration: {type: Date, required: true}
}, { strict: false });
对不起,如果代码中有些重复。 预先感谢您的帮助。