Node.js 如何在Mongoose模式中定义嵌套的非必填字段;“类型”;所有物
我的项目中有以下Mongoose模式定义:Node.js 如何在Mongoose模式中定义嵌套的非必填字段;“类型”;所有物,node.js,mongodb,typescript,mongoose,mongoose-schema,Node.js,Mongodb,Typescript,Mongoose,Mongoose Schema,我的项目中有以下Mongoose模式定义: export const ProductSchema:SchemaDefinition={ 类型:{type:String,enum:constants.productTypes,必需:true}, 名称:{type:String,必需:false}, espData:{ 类型:{type:String,必需:true}, 文本:{type:String,必需:true} }, 错误:{ 类型:{ 消息:{type:String,必需:true}, 状
export const ProductSchema:SchemaDefinition={
类型:{type:String,enum:constants.productTypes,必需:true},
名称:{type:String,必需:false},
espData:{
类型:{type:String,必需:true},
文本:{type:String,必需:true}
},
错误:{
类型:{
消息:{type:String,必需:true},
状态代码:{type:Number,默认值:null}
},
必填项:false
}
//更多的定义。。。
};
这里重要的是,我有一个产品集合,其中每个产品都有自己的类型
(这是一个必需的字符串属性,可以在常量.productTypes
中定义值),一个非必需的名称
字段,等等。另外,还有一个espData
字段,它有自己的强制type
属性,这与顶级type
完全不同。还有一个error
属性并不总是存在,但当它存在时,它必须具有message
属性和可选的statusCode
属性
我现在必须修改此模式,以便espData
成为可选字段,因为我现在可能有不具有此属性的产品。我该怎么做?我尝试了两种方法,但都不奏效:
- 首先,我修改了
,使其看起来与espData
相同:error
espData:{
类型:{
类型:{type:String,必需:true},
文本:{type:String,必需:true}
},
必填项:false
},
但是,这不起作用,很可能是因为有太多嵌套的type
属性。有趣的是,它完全适用于error
属性,该属性的结构与espData
相同,但没有嵌套的type
属性。我使用的代码是
const model=newthis.factories.product.model();
model.type=‘高智商’;
//model.espData故意未定义
等待model.save();
我得到的错误是产品验证失败:espData.type.text:Path'espData.type.text'是必需的,espData.type.type:Path'espData.type.type'是必需的。
这表示从架构创建的模型创建为espData.type.type
,这不是我想要的(我想要espData.type
)
- 第二,我从上面尝试了相同的方法,只是没有使用
required
字段,而是写了:default:null
,这给了我一个错误TypeError:schema路径“espData.default”的无效值,得到了值“null”
那么,如何将espData
定义为可选字段,当它存在时必须具有类型
和文本
属性?这就是您想要的。创建一个包含所有验证的新文档架构,并将其嵌套在另一个架构中,并使用required:false
(默认值为false)
范例
export const ProductSchema = new Schema({
...
espData: {
type: EspDataSchema,
required: false
},
...
})
是的,这是我需要的东西。我也尝试过类似的方法,但没有使用newschema()
。我刚刚提取了EspDataSchema
如下:const-EspDataSchema:SchemaDefinition={type:{type:String,…
,但它并没有真正起作用。谢谢!
export const ProductSchema = new Schema({
...
espData: {
type: EspDataSchema,
required: false
},
...
})