在Mongoose中验证对象数组可以通过使用Mongoose的内置验证器和自定义验证函数来实现。下面是一个完善且全面的答案:
在Mongoose中验证对象数组的步骤如下:
const mongoose = require('mongoose');
const itemSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
quantity: {
type: Number,
required: true
}
});
const mySchema = new mongoose.Schema({
items: {
type: [itemSchema],
required: true
}
});
const MyModel = mongoose.model('MyModel', mySchema);
const myObject = new MyModel({
items: [
{ name: 'Item 1', quantity: 5 },
{ name: 'Item 2', quantity: 10 }
]
});
myObject.validate((error) => {
if (error) {
console.log(error);
} else {
console.log('Validation passed');
}
});
itemSchema.path('quantity').validate(function(value) {
return value >= 0;
}, 'Quantity must be a non-negative number');
myObject.validate((error) => {
if (error) {
console.log(error);
} else {
console.log('Validation passed');
}
});
在上述代码中,我们创建了一个包含对象数组的模式(Schema),其中每个对象都有一个名称(name)和数量(quantity)。我们使用Mongoose的内置验证器来确保对象数组的属性是必需的,并使用自定义验证函数来验证数量属性是否为非负数。
这样,当我们创建一个新的MyModel对象并调用validate方法时,Mongoose会自动执行验证过程。如果验证失败,将返回一个错误对象,否则将输出"Validation passed"。
对于Mongoose中验证对象数组的完善且全面的答案,推荐的腾讯云相关产品是腾讯云数据库MongoDB,它是一种高性能、可扩展、全球分布的NoSQL数据库服务,适用于各种规模的应用程序。您可以通过以下链接了解更多信息:腾讯云数据库MongoDB。
领取专属 10元无门槛券
手把手带您无忧上云