如何在Mongoose中验证数组,同时验证其元素

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

本文关键字:验证 元素 数组 Mongoose      更新时间:2023-09-26

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

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

例如,我想根据需要放置book数组。有什么帮助吗?

您可以使用自定义验证器来完成此操作。只需检查数组本身是否为空:

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

当数组中没有内容时,这将引发错误,否则将通过对为数组中字段提供的规则的验证。