如何定义猫鼬模式中对象数组的最小长度?
Posted
技术标签:
【中文标题】如何定义猫鼬模式中对象数组的最小长度?【英文标题】:How to define the minimum length of array of objects in mongoose schema? 【发布时间】:2021-06-23 00:02:26 【问题描述】:我有我的问题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;
我希望每个问题至少有两个选项,如何在上面的“选项”字段中实现这一点。
【问题讨论】:
【参考方案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']
);
解决方案 2
questionSchema.path('options')
.validate((val) -> val.length > 1, 'Must have minimum two options');
参考
SchemaType.prototype.validate()
Array size in Mongoose schema
【讨论】:
以上是关于如何定义猫鼬模式中对象数组的最小长度?的主要内容,如果未能解决你的问题,请参考以下文章