使用mongoose查询验证对象

时间:2017-02-26 11:48:28

标签: javascript node.js mongodb express mongoose

我需要使用mongoose查询验证对象。

例如,我有对象:

const user = {username: 'foo', email: 'foo@mail', type: 2};

和猫鼬查询

const query = { type: { '$in': [ 2, 1 ] };

所以我需要这样的东西:

const isValid = validate(user, query);  // true

1 个答案:

答案 0 :(得分:0)

要验证您的数据,您可以使用built-in validators,如果您需要指定范围:

var DataSchema = new mongoose.Schema({
    username: String,
    email: String,
    type: {
        type: Number,
        min: [1, 'Error type must be > 0'],
        max: [2, 'Error type must be < 3']
    }
});

custom validators,如果要检查数组中的值:

var acceptedTypes = [2, 1];

var DataSchema = new mongoose.Schema({
    username: String,
    email: String,
    type: {
        type: Number,
        validate: {
            validator: function(v) {
                for (var i = 0; i < acceptedTypes.length; i++) {
                    return (acceptedTypes[i] == v);
                }
                return false;
            },
            message: '[type] is not an accepted value'
        }
    }
});