我将只更改角色的book_mode字段和状态的book_mode字段,但是执行findOneAndUpdate()之后,角色和状态的patrol_mode字段消失了。我想保留那个领域。我该怎么办?
var userSchema = new Schema({
user_id: String,
name: String,
avatar: String,
role: {
book_mode: Number,
patrol_mode: Number
},
status: {
book_mode: Number,
patrol_mode: Number
},
created_at: Number,
updated_at: Number
}, {collection: 'users'});
var updateData = {
status: {
book_mode: APPROVED
},
role: {
book_mode: req.body.role
}
}
User.findOneAndUpdate({
_id: mongoose.Types.ObjectId(req.body._id)
},
{$set: updateData},
function(err, doc){
if(err){
resData.message = 'failed';
resData.code = 501;
resData.flag = false;
resData.data = err;
res.send(resData);
return;
}
resData.data = doc;
resData.message = 'success';
resData.code = 200;
resData.flag = true
res.send(resData);
return;
});
答案 0 :(得分:0)
因为您将整个父对象重新分配为仅包含book_mood,所以可以使用点符号来访问特定字段。
updateData = {
"status.book_mode": APPROVED,
"role.book_mode": req.body.rol
}
那是如果APPROVED和req.body.rol包含book_mood的字符串,如果它包含一个对象,那么您必须将其更改为
updateData = {
"status.book_mode": APPROVED.book_mode,
"role.book_mode": req.body.rol.book_mode
}