Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate in Mongoose an array and the same time its elements

I have this schema where I validated the elements of array book, but I don't know how to validate the array itself.

 var DictionarySchema = new Schema({   
        book: [
            {              
                1: {
                    type: String,
                    required: true
                },
                2: String,
                3: String,
                c: String,
                p: String,
                r: String
            }
        ]
    });

For example, I would like to put the book array as required. Any help?

like image 692
in3pi2 Avatar asked Feb 12 '23 23:02

in3pi2


1 Answers

You can use a custom validator to do this. Simply check that the array itself is not empty:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/test');

var bookSchema = new Schema({

  1: { type: String, required: true },
  2: String,
  3: String,
  c: String,
  p: String,
  r: String
});

var dictSchema = new Schema({
  books: [bookSchema]
});

dictSchema.path('books').validate(function(value) {
  return value.length;
},"'books' cannot be an empty array");

var Dictionary = mongoose.model( 'Dictionary', dictSchema );


var dict = new Dictionary({ "books": [] });


dict.save(function(err,doc) {
  if (err) throw err;

  console.log(doc);

});

Which will throw an error when there is no content in the array, and otherwise pass off the validation for the rules supplied for the fields in the array.

like image 182
Neil Lunn Avatar answered Feb 14 '23 17:02

Neil Lunn