猫鼬.update()不会触发验证检查 [英] Mongoose .update() does not trigger validation checking

查看:94
本文介绍了猫鼬.update()不会触发验证检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在枚举数组之外设置值,但我不知道为什么猫鼬不验证该值,我是否以错误的方式更新了枚举?

I can set values beyond the enum array and I do not know why mongoose not validate the value, am I do update the enum in wrong way?

我的代码:

var OrderSchema = new mongoose.Schema({
status:{type:String,enum:['created','shipped','confirmed']},
)};

var changeOrderStatus = function(shopId,orderId,status,callback){

    Order.update({_id:orderId,shop:shopId},{$set:{status:status}},{upsert:false},
        function(err){

            console.log(err);
            callback(err);

    })
}

状态枚举应该仅对以下三个值有效:['已创建','已发货','已确认']

The status enum should only have value for the three:['created','shipped','confirmed']

但是我可以做到:

推荐答案

在4.0版之前的猫鼬不支持对Schema静态方法(如.update.findByIdAndUpdate.findOneAndUpdate)进行验证.

Mongoose before version 4.0 didn't support validation on Schema static methods like .update, .findByIdAndUpdate, .findOneAndUpdate.

但是它支持实例方法document.save()

因此,首先您需要找到一个订单,然后更改所需的属性并调用.save().像这样:

So first you need to find an order and then change property you want and call .save(). Like this:

Order.findOne({ _id: orderId, shop: shopId }, function(err, order) {
  order.status = 'foo';
  order.save(function(err, savedOrder) {
    // ERROR HERE
  })
})

如果使用Mongoose 4.0,则在更新调用中包含runValidators: true选项时,它支持Schema.update$set字段的Schema.update中的验证.

If you use Mongoose 4.0 it supports the validation in Schema.update of the fields of $set and $unset operators when you include the runValidators: true option in the update call.

因此您的更新将如下所示:

So your updating will look like this:

Order.update(
  { _id: orderId, shop: shopId },
  { $set: { status: status }},
  { upsert: true, runValidators: true }, function(err) {
    console.log(err);
    callback(err);
}

这篇关于猫鼬.update()不会触发验证检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆