使用猫鼬添加不在模式中的字段
问题描述:
我正在尝试向文档添加一个新字段,但这不起作用:
I am trying to add a new field to a document, but this isn't working:
创建我的 UserModel 原型:
Creating my UserModel prototype:
model = require("../models/user")
UserModel.prototype.findOneAndUpdate = function(query, params, cb) {
model.findOneAndUpdate(query, params, { returnNewDocument: true, new: true }, function(err, data) {
if (!err) {
cb(false, data);
} else {
cb(err, false);
}
});
};
然后调用它
userFunc = require("../../model_functions/user")
userFunc.findOneAndUpdate({
"email.value": userEmail
}, {
$set: {"wat":"tf"}
},
function (err, updatedUser) {
//This logs the updated user just fine, but the new field is missing
console.log(updatedUser);
...
});
这会成功更新任何存在的字段,但不会添加任何新字段.
This successfully updates any field as long as it exists, but it won't add any new one.
答
您可以使用选项 { strict: false }
选项:严格
strict 选项(默认启用)确保传递给的值我们的模式中未指定的模型构造函数没有得到保存到数据库中.
The strict option, (enabled by default), ensures that values passed to our model constructor that were not specified in our schema do not get saved to the db.
var thingSchema = new Schema({..}, { strict: false });
您也可以在更新查询中执行此操作
And also you can do this in update query as well
Model.findOneAndUpdate(
query, //filter
update, //data to update
{ //options
returnNewDocument: true,
new: true,
strict: false
}
)
您可以在此处查看文档