Yan Li
Yan Li

Reputation: 1819

Mongoose .update() does not trigger validation checking

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?

my code:

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']

but I could do:

enter image description here

Upvotes: 7

Views: 3472

Answers (1)

Max
Max

Reputation: 1844

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

But it supports on instance method document.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
  })
})

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

Upvotes: 17

Related Questions