gpt4 book ai didi

mongoose - 为什么 Mongoose 不验证更新?

转载 作者:行者123 更新时间:2023-12-02 16:13:19 26 4
gpt4 key购买 nike

我有这个代码

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) {
....
});

如果我将表单上的名称字段保留为空, Mongoose 将不允许创建客户端,因为我根据架构上的要求进行了设置。另外,如果我在名称前后留下空格, Mongoose 会在保存之前删除该空格。

现在,我尝试使用此代码更新客户端

var id = req.params.id;
var client = req.body;
Client.update({_id: id}, client, function(err) {
....
});

它允许我更改名称,但如果我在表单上将其保留为空, Mongoose 不会验证并保存空名称。如果我在名称前后添加空格,则会用空格保存名称。

为什么 Mongoose 在保存时验证而不是在更新时验证?我的方法不对吗?

mongodb:2.4.0 Mongoose :3.6.0 express :3.1.0节点:0.10.1

最佳答案

从 Mongoose 4.0 开始,您 can run validatorsupdate()findOneAndUpdate() 上使用新标志 runValidators: true

Mongoose 4.0 introduces an option to run validators on update() andfindOneAndUpdate() calls. Turning this option on will run validatorsfor all fields that your update() call tries to $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) {
....
});

pre Hook 上使用标志

如果您不想每次更新内容时都设置该标志,可以为 findOneAndUpdate() 设置一个 pre Hook :

// Pre hook for `findOneAndUpdate`
ClientSchema.pre('findOneAndUpdate', function(next) {
this.options.runValidators = true;
next();
});

然后您可以使用验证器update(),而无需每次都传递runValidators 标志。

关于mongoose - 为什么 Mongoose 不验证更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15627967/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com