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)
例如,我想根据需要放置书籍数组.有帮助吗?
您可以使用自定义验证程序执行此操作.只需检查数组本身是否为空:
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)
当数组中没有内容时会抛出错误,否则将为为数组中的字段提供的规则传递验证.
| 归档时间: |
|
| 查看次数: |
3933 次 |
| 最近记录: |