如何在Mongoose中验证数组及其元素

4

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

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

例如,我想按要求放置书籍数组。有什么帮助吗?
1个回答

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

});

当数组中没有内容时,它会抛出一个错误,否则会将规则验证传递给数组中的字段。


谢谢,这非常有用!但是,还有另一种内联方式将验证传递给数组book。因为有时需要使用其他不同的过滤器来required,例如(maxminexpiresenumlowercasematchtrimuppercase等),这些已经由mongoose提供,我认为在validate()函数中实现它可能效率低下。 - in3pi2
2
@in3pi2 这就是所有内置类型和规则的验证方式,而mongoose API只是公开了内部方法,以便您可以“插入”其中。还请参阅文档中的插件 - Neil Lunn
1
因为mongoose默认会这样做。但是你可以关闭它。阅读文档,如果有其他问题,请提出另一个问题,而不是发表评论。 - Neil Lunn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接