如何验证$ push in update request mongoose?

时间:2018-03-30 10:34:37

标签: node.js mongodb rest api mongoose-schema

我的猫鼬模式是

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

验证函数maxOption在发布请求时工作正常。它不允许数组大小超过3.但是当它是更新请求时,验证不起作用。我们知道,runValidation仅适用于$ set / $ unset。如何在更新时验证这一点?

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

为了更加清晰,更新时不会验证arraylength。这意味着我可以在更新时添加任意数量的元素,但对于POST,它可以正常工作。

0 个答案:

没有答案