PH Andrade
PH Andrade

Reputation: 43

validate array content mongoose model

I have an mongoose model like this

   valid_days: {
    type: [Number]
  },

but I want to validade if array match the following example:

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

or some combination of this, like

[1,3,5]

how could I do this with mongoose?

Upvotes: 3

Views: 1316

Answers (1)

Bertrand Martel
Bertrand Martel

Reputation: 45352

You can use mongoose custom validators and validate only some values in your array :

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

For this example :

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

Upvotes: 4

Related Questions