Search code examples
node.jsmongodbrestapimongoose-schema

How validate $push in update request mongoose?


My mongoose schema is

function maxOption(val) {
    return val.length <= 3;
}

const OptionSchema = new Schema({ 
    name: {
        type: String,
        required: [true, 'Option name is required.']
    },
    pos: Number,
    values: [
        String
    ] 
});

const ProductSchema = new Schema({  
    title: {
        type: String,
        required: [true, 'Product title is required.']
    },
    options: {
        type: [ OptionSchema ],
        validate: [ maxOption, '{PATH} exceeds the limit of 3']
    } 
});

The validation function maxOption works fine when it is a post request. It does not allow array size more than 3. But when it is an update request, the validation does not work. As we know, runValidation is only work on $set/$unset. How can I validate this while updating?

var variant = req.body;  
var pushOpt = { options: variant.options };
    
if(variant.options) {
    Product.findByIdAndUpdate({
        _id: req.params.id
    }, {$push: pushOpt }).then(function(){
        Product.findOne({
            _id: req.params.id
        }).then(function(product){
            res.send(product);
        });
    }).catch(next);
}

For more clarity, when updating it does not validate the arraylength. That means I can add as many elements as I wish while updating but for POST it works fine.


Solution

  • Update validators need to be turned on, they are turned off by default per mongoose update documentation

    Edit: Another thing to keep in mind is that array validations are not run on $push operations (and a few others), in a case like this you may need to rewrite validators to execute on the elements of the array instead of the entire array itself