[英]How to define the minimum length of array of objects in mongoose schema?
I have my questionsModel.js as such我有我的问题Model.js 这样
const mongoose = require('mongoose');
const validator = require('validator');
const questionSchema = new mongoose.Schema({
question: {
type: String,
required: [true, 'Question Required'],
trim: true
},
options: [ // this array should atleast have two objects meaning two options
{
optionNo: Number,
optionValue:{
type: String,
required: [true,'Option required'],
trim: true
}
},
]
});
const Question = mongoose.model('Question', questionSchema);
module.exports = Question;
I want to have minimum two options for each question how do I implement this in the "options" field above.我希望每个问题至少有两个选项,如何在上面的“选项”字段中实现这一点。
Solution 1解决方案 1
const questionSchema = new mongoose.Schema({
question: {
type: String,
required: [true, 'Question Required'],
trim: true
},
options: {
type: [{
optionNo: Number,
optionValue:{
type: String,
required: [true,'Option required'],
trim: true
}
}],
validate: [(val) -> val.length > 1, 'Must have minimum two options']
}
});
Solution 2解决方案 2
questionSchema.path('options')
.validate((val) -> val.length > 1, 'Must have minimum two options');
Reference参考
SchemaType.prototype.validate() SchemaType.prototype.validate()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.