首页 > 解决方案 > 如何使用嵌套的“类型”属性在 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: {
    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)。

那么,如何定义espData为可选字段,它存在时必须具有typetext属性?

标签: node.jsmongodbtypescriptmongoosemongoose-schema

解决方案


这是你想要的吗。创建一个包含所有验证的新文档模式并将其嵌套在另一个模式中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
   },

...

})

推荐阅读