【问题标题】:Mongoose .update() does not trigger validation checkingMongoose .update() 不会触发验证检查
【发布时间】:2016-10-03 12:45:05
【问题描述】:

我可以设置超出枚举数组的值,但我不知道为什么 mongoose 不验证值,我是否以错误的方式更新枚举?

我的代码:

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);

    })
}

status 枚举应该只对以下三个有值:['created','shipped','confirmed']

但我可以:

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    4.0 版之前的 Mongoose 不支持对 .update.findByIdAndUpdate.findOneAndUpdate 等 Schema 静态方法进行验证。

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

    所以首先您需要找到一个订单,然后更改您想要的属性并致电.save()。像这样:

    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$unset 运算符的字段。

    所以您的更新将如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-26
      • 2015-07-20
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      相关资源
      最近更新 更多