Pizzicato
Pizzicato

Reputation: 1621

Mongoose: Validation not being executed when saving

I've defined this Mongoose schema:

// validator function
var arrayWithAtLeastFiveElements = function (a) {
    return (a !== undefined && a.length >= 5);
};

var orderSchema = new Schema({
    user: {
        type: Schema.ObjectId,
        ref: User,
        required: true
    },
    products: [{
        type: Schema.ObjectId,
        ref: Product,
        required: true,
        validate: [arrayWithAtLeastFiveElements, 'Order needs to have at least five products']
    }]
}, {
    timestamps: {
        createdAt: 'created_at',
        updatedAt: 'updated_at'
    }
});

When I try to save it, the validation is not executed if products is undefined, null or an empty array, and it saves the new order with an empty array of products in each case. The validations are only run when products is an array with at least one element. Any clue what's going on? It there a way to make the validation run in all cases? Also, what does require do in this case? I don't see any change in validations if I define products array as required or not...

Upvotes: 0

Views: 373

Answers (1)

Amiram Korach
Amiram Korach

Reputation: 13296

Define it with:

products: {
   type: [Schema.ObjectId],
   required: true,
}

Upvotes: 1

Related Questions