Pizzicato Pizzicato - 1 year ago 67
Node.js Question

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
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
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...

Answer Source

Define it with:

products: {
   type: [Schema.ObjectId],
   required: true,
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download