问题描述
我有这个代码
var ClientSchema = new Schema({名称:{类型:字符串,必需:真,修剪:真}});var Client = mongoose.model('Client', ClientSchema);
使用 express,我使用此代码创建了一个新客户端
var client = new Client(req.body);客户端.保存(功能(错误,数据){....});
如果我将表单上的 name 字段留空,mongoose 将不允许创建客户端,因为我根据架构的要求进行了设置.此外,如果我在名称前后留有空格,猫鼬会在保存前删除该空格.
现在,我尝试使用此代码更新客户端
var id = req.params.id;var 客户端 = req.body;Client.update({_id: id}, client, function(err) {....});
它允许我更改名称,但如果我在表单上将其留空,猫鼬不会验证并保存空名称.如果我在名称前后添加空格,它会用空格保存名称.
为什么猫鼬在保存时验证而不是在更新时验证?我做错了吗?
mongodb:2.4.0猫鼬:3.6.0快递:3.1.0节点:0.10.1
你没有做错任何事,validation
在 Mongoose 中作为内部中间件实现,中间件不会在 update
期间执行,因为这基本上是对本机驱动程序的传递.>
如果您希望您的客户端更新得到验证,您需要find
要更新的对象,将新的属性值应用到它(请参阅下划线的 extend
方法),然后对其调用 save
.
猫鼬 4.0 更新
如评论和 victorkohl 的回答所述,Mongoose 现在支持在包含 runValidators 时验证
选项.$set
和 $unset
运算符的字段:update
调用中的 true
I have this code
var ClientSchema = new Schema({
name: {type: String, required: true, trim: true}
});
var Client = mongoose.model('Client', ClientSchema);
Using express, I create a new client with this code
var client = new Client(req.body);
client.save(function(err, data) {
....
});
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.0mongoose: 3.6.0express: 3.1.0node: 0.10.1
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.
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.
Mongoose 4.0 Update
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.
这篇关于为什么猫鼬不验证更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!