【问题标题】:Set `required` for object type field in Mongoose为 Mongoose 中的对象类型字段设置“必需”
【发布时间】:2019-07-03 03:58:40
【问题描述】:

这个很好用:

{
  name: {
    first: { type: String, required: true },
    last: { type: String, required: true }
  }
}

但是这个不行

{
  name: {
    required: true,
    first: { type: String },
    last: { type: String }
  }
}

它甚至不会开始:

/Users/albertgao/codes/temp/aaa/node_modules/mongoose/lib/schema.js:751 throw new TypeError(Invalid schema configuration: \${name}` is not ` + ^

TypeError:无效的架构配置:True 不是路径 name.required 上的有效类型。

如何说我希望name 是必需的而不设置其每个子字段?

谢谢

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    问题是 field:TYPE 的简写,它不应该与必需的选项字段混合。相反,我认为您可以尝试不在父字段中使用速记,如下所示:

    {
      name: {
        type: { 
           first: String,
           last: String
       },
       required: true
    }
    

    甚至更明确:

    {
      name: {
        type: { 
           first: { type: String},
           last: { type: String}
       },
       required: true
    }
    

    【讨论】:

      猜你喜欢
      • 2012-09-20
      • 2019-01-19
      • 1970-01-01
      • 2017-06-12
      • 2014-10-15
      • 1970-01-01
      • 2016-04-11
      • 2013-02-12
      相关资源
      最近更新 更多