node.js - 如何使用嵌套的“类型”属性在 Mongoose 模式中定义非必填字段?
问题描述
我的项目中有以下 Mongoose 模式定义:
export const ProductSchema: SchemaDefinition = {
type: { type: String, enum: constants.productTypes, required: true },
name: { type: String, required: false },
espData: {
type: { type: String, required: true },
text: { type: String, required: true }
},
error: {
type: {
message: { type: String, required: true },
statusCode: { type: Number, default: null }
},
required: false
}
// Some more definitions...
};
从这里开始重要的是,我收集了每个产品都有自己的产品type
(这是一个必需的字符串属性,可以在 中定义值constants.productTypes
),一个非必需的name
字段等等。此外,还有一个espData
字段有自己的强制type
属性,它与顶层完全不同type
。并且,有error
属性并不总是存在,但当它存在时,它必须具有message
属性和可选statusCode
属性。
我现在必须修改此架构,使其espData
成为可选字段,因为我现在可能拥有不具有此属性的产品。我怎么做?我尝试了几件事,但都没有奏效:
- 首先,我进行了修改
espData
,使其看起来与以下内容相同error
:
espData: {
type: {
type: { type: String, required: true },
text: { type: String, required: true }
},
required: false
},
但是,这不起作用,很可能是因为有太多嵌套type
属性。有趣的是,它非常适用于与error
具有相同结构espData
但没有嵌套属性的type
属性。我使用的代码是
const model = new this.factories.product.model();
model.type = 'hi-iq';
// model.espData purposely left undefined
await model.save();
我得到的错误是Product validation failed: espData.type.text: Path 'espData.type.text' is required., espData.type.type: Path 'espData.type.type' is required.
这表明model
从模式创建espData.type.type
的不是我想要的(我想要的espData.type
)。
- 其次,我从上面尝试了相同的方法,只是
required
我写了:default: null
这给了我一个错误,而不是字段TypeError: Invalid value for schema path 'espData.default', got value "null"
。
那么,如何定义espData
为可选字段,它存在时必须具有type
和text
属性?
解决方案
这是你想要的吗。创建一个包含所有验证的新文档模式并将其嵌套在另一个模式中required: false
(无论如何默认为 false)
const EspDataSchema = new Schema({
type: { type: String, required: true },
text: { type: String, required: true },
},
{
_id: false,
}
);
例子
export const ProductSchema = new Schema({
...
espData: {
type: EspDataSchema,
required: false
},
...
})
推荐阅读
- javascript - 使用 d3 创建条形图
- heroku - 在 /.well-known/assetlinks.json 上找不到 404
- css - 具有多个角度的 CSS 渐变
- javascript - webpack 可以改变资产的来源吗?
- terraform - Terraform:来自多个模块调用的输出
- javascript - React Native Typescript Typing for "Backwards" ScrollView
- python - TKinter 画布的透明背景
- python - numpy searchsorted with side='right' on numpy.arange,给出不正确的结果
- reactjs - 如何在本机反应中使用按钮向下移动对象?
- r - 计算平均发动机预期寿命之间的比率