【问题标题】:How validate $push in update request mongoose?如何在更新请求 mongoose 中验证 $push?
【发布时间】:2022-05-11 11:01:42
【问题描述】:

我的猫鼬模式是

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

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

【问题讨论】:

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


    【解决方案1】:

    更新验证器需要开启,mongoose update documentation默认关闭

    编辑:要记住的另一件事是数组验证不会在 $push 操作(以及其他一些操作)上运行,在这种情况下,您可能需要重写验证器以在数组元素上执行而不是整个数组本身

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-26
      • 2021-08-05
      • 1970-01-01
      • 2015-09-29
      • 2023-03-27
      • 2021-03-23
      • 1970-01-01
      • 2019-11-11
      相关资源
      最近更新 更多