admin管理员组文章数量:1332345
I have this schema where I validated the elements of array book
, but I don't know how to validate the array itself.
var DictionarySchema = new Schema({
book: [
{
1: {
type: String,
required: true
},
2: String,
3: String,
c: String,
p: String,
r: String
}
]
});
For example, I would like to put the book array as required. Any help?
I have this schema where I validated the elements of array book
, but I don't know how to validate the array itself.
var DictionarySchema = new Schema({
book: [
{
1: {
type: String,
required: true
},
2: String,
3: String,
c: String,
p: String,
r: String
}
]
});
For example, I would like to put the book array as required. Any help?
Share Improve this question edited Jun 28, 2017 at 2:27 Neil Lunn 151k36 gold badges355 silver badges325 bronze badges asked Sep 22, 2014 at 1:21 in3pi2in3pi2 9071 gold badge11 silver badges22 bronze badges1 Answer
Reset to default 8You can use a custom validator to do this. Simply check that the array itself is not empty:
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);
});
Which will throw an error when there is no content in the array, and otherwise pass off the validation for the rules supplied for the fields in the array.
本文标签: javascriptHow to validate in Mongoose an array and the same time its elementsStack Overflow
版权声明:本文标题:javascript - How to validate in Mongoose an array and the same time its elements - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742324196a2453393.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论