【问题标题】:validate array content mongoose model验证数组内容猫鼬模型
【发布时间】:2017-06-30 00:20:10
【问题描述】:

我有一个像这样的猫鼬模型

   valid_days: {
    type: [Number]
  },

但我想验证数组是否与以下示例匹配:

[1,2,3,4,5,6,7]

或者这些的组合,比如

[1,3,5]

我怎么能用猫鼬做到这一点?

【问题讨论】:

    标签: arrays validation mongoose schema


    【解决方案1】:

    您可以使用mongoose custom validators 并仅验证数组中的某些值:

    var possibilities = [1, 2, 3, 4, 5, 7];
    
    var testSchema = new mongoose.Schema({
        valid_days: {
            type: [Number],
            validate: {
                validator: function(value) {
                    for (var i = 0; i < value.length; i++) {
                        if (possibilities.indexOf(value[i]) == -1) {
                            return false;
                        }
                    }
                    return true;
                },
                message: '{VALUE} is not a valid day'
            }
        },
    });
    

    对于这个例子:

    Test.create({ "valid_days": [1, 3, 5, 6] }, function(err, res) {
        // this trigger error : 6 not in possibilities array
        if (err)
            console.log(err);
        else
            console.log("OK");
    });
    
    Test.create({ "valid_days": [1, 3, 5] }, function(err, res) {
        // ok 1,3,5 are in possibilities array
        if (err)
            console.log(err);
        else
            console.log("OK");
    });
    

    【讨论】:

    • 非常感谢!正是我需要的!
    猜你喜欢
    • 1970-01-01
    • 2014-08-21
    • 2016-09-23
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    相关资源
    最近更新 更多