我有这个代码
var ClientSchema = new Schema({
name: {type: String, required: true, trim: true}
});
var Client = mongoose.model('Client', ClientSchema);
使用express,我使用此代码创建一个新客户端
var client = new Client(req.body);
client.save(function(err, data) {
....
});
如果我将表单上的名称字段留空,猫鼬将不允许创建客户端,因为我根据架构上的要求进行了设置。另外,如果我在名称前后留下空格,猫鼬会在保存之前删除该空格。
现在,我尝试使用此代码更新客户端
var id = req.params.id;
var client = req.body;
Client.update({_id: id}, client, function(err) {
....
});
它允许我更改名称,但如果我在表单上将其保留为空,猫鼬不会验证并保存空名称。如果我在名称前后添加空格,则会用空格保存名称。
为什么猫鼬在保存时验证而不是在更新时验证?我以错误的方式做这件事吗?
MongoDB:2.4.0
猫鼬:3.6.0
快递:3.1.0
节点:0.10.1
从 Mongoose 4.0 开始,您可以运行验证器 http://www.mongodb.com/blog/post/introducing-version-40-mongoose-nodejs-odm on update()
and findOneAndUpdate()
使用新标志runValidators: true
.
Mongoose 4.0 引入了运行验证器的选项update()
and
findOneAndUpdate()
来电。打开此选项将运行验证器
对于您的所有领域update()
呼叫尝试$set
or $unset
.
例如,给定 OP 的架构:
const ClientSchema = new Schema({
name: {type: String, required: true, trim: true}
});
const Client = mongoose.model('Client', ClientSchema);
每次更新时传递标志
您可以像这样使用新标志:
const id = req.params.id;
const client = req.body;
Client.update({_id: id}, client, { runValidators: true }, function(err) {
....
});
在 a 上使用该标志pre
hook
如果您不想每次更新内容时都设置标志,您可以设置pre
钩子findOneAndUpdate()
:
// Pre hook for `findOneAndUpdate`
ClientSchema.pre('findOneAndUpdate', function(next) {
this.options.runValidators = true;
next();
});
然后你可以update()
使用验证器而不通过runValidators
每次都会标记。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)