如何在Mongoose中验证一个数组并同时对其元素进行验证

in3*_*pi2 4 javascript mongoose mongodb node.js mongodb-query

我有这个模式,我验证了数组的元素book,但我不知道如何验证数组本身.

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

例如,我想根据需要放置书籍数组.有帮助吗?

Nei*_*unn 8

您可以使用自定义验证程序执行此操作.只需检查数组本身是否为空:

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

});
Run Code Online (Sandbox Code Playgroud)

当数组中没有内容时会抛出错误,否则将为为数组中的字段提供的规则传递验证.

  • @ in3pi2无论如何,这是对所有内置类型和规则进行验证的方式,而mongoose API只是公开了内部方法,因此您可以"插入"它.另请参阅文档中的[plugins](http://mongoosejs.com/docs/plugins.html). (2认同)