【问题标题】:How to require a nested json object in Mongoose Schema如何在 Mongoose Schema 中要求嵌套的 json 对象
【发布时间】:2020-06-15 04:43:59
【问题描述】:

我有以下猫鼬模式:

const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 1,
    maxlength: 255
  },
  extraData: {
    brand: {
      type: String,
      required: true,
      minlength: 1,
      maxlength: 255
    },
    quantity: {
      type: Number,
      required: true,
      minlength: 1,
      maxlength: 10
    },
   required: true
  }
});

但是,当我执行它时,我收到以下错误:“TypeError: Invalid schema configuration: True is not a valid type at path extraData.required”。我怎样才能要求 extraData?

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    更新: 您可以使用Subdocument 方法

    const extraDataSchema = new mongoose.Schema({
      brand: {
        type: String,
        required: true,
        minlength: 1,
        maxlength: 255
      },
      quantity: {
        type: Number,
        required: true,
        minlength: 1,
        maxlength: 10
      }
    });
    
    const productSchema = new mongoose.Schema({
      name: {
        type: String,
        required: true,
        minlength: 1,
        maxlength: 255
      },
      extraData: {
        type: extraDataSchema, required: true
      }
    });
    

    【讨论】:

    • 当我使用这种方法时,我遇到了一些问题,但最终使 extraData: { type: extraDataSchema, required: true } 而不是 extraData: { type: Object, of: extraDataSchema, required: true } 正常工作。
    【解决方案2】:

    查看Mongoose documentation,在此链接中,您可以找到有关如何将required 添加到嵌套属性()的说明。
    我相信您将需要嵌套属性的子架构。

    【讨论】:

      猜你喜欢
      • 2019-10-22
      • 1970-01-01
      • 2020-12-26
      • 1970-01-01
      • 2016-05-06
      • 2017-09-16
      • 2017-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多