【问题标题】:Object inside a field of mongoose Schema猫鼬模式字段内的对象
【发布时间】:2020-10-26 07:35:59
【问题描述】:

我正在构建一个提供有关笔记本电脑的信息的 API。为此,我将 node 和 mongoDB 与 mongoose 一起使用。这是我的架构 -

const productSchema = mongoose.Schema(
{
    name: {
        type: String,
        required: [true, 'A product must have a name'],
        unique: true,
    },
},
{
    toJSON: {
        virtuals: true,
    },
    toObject: {
        virtuals: true,
    },
});

我有一个名称字段。我还想要一个应该是对象的“规格”字段。我想为“specs”字段的对象中的属性定义规则。我期望在规格领域出现的是 -

specs: {
   memory: "16gb",
   storage: "512gb",
   "processor": "i7 2.2ghz"
}

所以,我想在“specs”对象中定义“内存”、“存储”、“处理器”的规则

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    如果规则是指架构对象规则,那么可能会这样做:

    specs: {
        memory: {
          type: String,
          default: null
        },
        storage: {
          type: String,
          default: null
        },
        processor: {
          type: String,
          default: null
        }
    }
    

    您可以根据需要添加更多规则。

    【讨论】:

      猜你喜欢
      • 2018-10-15
      • 2021-04-10
      • 2019-10-30
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      • 2017-01-28
      • 1970-01-01
      • 2015-06-04
      相关资源
      最近更新 更多