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

人盡茶涼 提交于 2019-12-04 10:58:08

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!