Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose .update() does not trigger validation checking

Tags:

mongoose

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

like image 846
Yan Li Avatar asked Jun 03 '16 12:06

Yan Li


1 Answers

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);
}
like image 192
Max Avatar answered Oct 05 '22 23:10

Max