如何在Mongoose中验证数组,同时验证其元素
How to validate in Mongoose an array and the same time its elements
我在这个模式中验证了数组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);
});
当数组中没有内容时,这将引发错误,否则将通过对为数组中字段提供的规则的验证。
相关文章:
- 从所有元素中删除HTML5验证
- 在验证器中添加自定义规则以检查<ul>具有元素
- 使用jquery验证函数不适用于select元素
- validate.js验证数组元素
- 如何在JavaScript而不是HTML元素中设置AngularJS验证
- 使用webdriver和selenium验证元素是否不存在
- 如何对未知表单元素进行表单验证
- 验证元素值和复选框的Javascript
- 使用html 5对元素执行自定义表单验证功能
- Javascript:表单验证getElementById仅返回第一个id元素
- 表单元素值更改后的角度 JS 验证
- 如何在 angularjs 中验证元素指令
- 在验证元素是否存在时如何考虑 ng-if
- jQuery验证-元素未定义
- 如何使用javascript和localStorage验证元素是否存在于html中
- 在AngularJS动态电子邮件验证元素中,当我填写电子邮件检查元素时,它's重置
- 在添加到html页面之前验证元素是否存在
- 根据索引验证元素是否存在
- 在AngularJS中使用ng-disabled来验证元素集合时,会出现$rootScope:infdig错误
- 如何使用jquery验证元素列表