问题描述
我有这个代码
var ClientSchema = new Schema({
name: {type: String, required: true, trim: true}
});
var Client = mongoose.mode('Client', ClientSchema);
使用快递,我用此代码创建一个新客户端
Using express, I create a new client with this code
var client = new Client(req.body);
client.save(function(err, data) {
....
});
如果我在表单上将名称"字段留空,则mongoose不允许创建客户端,因为我已根据架构上的要求对其进行了设置.另外,如果我在名称的前后都留有空格,猫鼬会在保存之前删除该空格.
If I leave the name field empty on the form, mongoose doesn't allow to create the client because I set it as required on the schema. Also, if I leave spaces before and after the name, mongoose delete that spaces before save.
现在,我尝试使用此代码更新客户端
Now, I try to update a client with this code
var id = req.params.id;
var client = req.body;
Client.update({_id: id}, client, function(err) {
....
});
它允许我更改名称,但是如果我在表单上将其保留为空白,猫鼬将不会验证并保存一个空名称.如果我在名称前后添加空格,则会使用空格保存名称.
It let me to change the name, but if I leave it empty on the form, mongoose doesn't validate and save an empty name. If I add empty spaces before and after the name, it save the name with spaces.
为什么猫鼬在保存时验证而不在更新时验证?我做错了吗?
Why mongoose validate on save but not on update? I'm doing it in the wrong way?
mongodb:2.4.0猫鼬:3.6.0快递:3.1.0节点:0.10.1
mongodb: 2.4.0mongoose: 3.6.0express: 3.1.0node: 0.10.1
推荐答案
您没有做错任何事情, validation
被实现为Mongoose中的内部中间件,并且在update
期间不会执行中间件,因为这基本上是对本机驱动程序的传递.
You're not doing anything wrong, validation
is implemented as internal middleware within Mongoose and middleware doesn't get executed during an update
as that's basically a pass-through to the native driver.
如果要验证客户端更新,则需要find
要更新的对象,对其应用新的属性值(请参见下划线的 extend
方法),然后在其上调用save
.
If you want your client update validated you'll need to find
the object to update, apply the new property values to it (see underscore's extend
method), and then call save
on it.
猫鼬4.0更新
正如评论和victorkohl的回答所述,当您在update
调用中包含runValidators: true
选项时,猫鼬现在支持验证$set
和$unset
运算符的字段.
As noted in the comments and victorkohl's answer, Mongoose now support the validation of the fields of $set
and $unset
operators when you include the runValidators: true
option in the update
call.
这篇关于为什么猫鼬不更新验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!