在猫鼬中为对象类型字段设置`required`

时间:2019-02-08 21:19:36

标签: mongoose

这个很好用:

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

但是这个不起作用

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

它甚至不会开始:

  

/用户/ albertgao /代码/temp/aaa/node_modules/mongoose/lib/schema.js:751       抛出新的TypeError(Invalid schema configuration: \ $ {name}`不是`+       ^

     

TypeError:模式配置无效:True在路径name.required处不是有效类型。

怎么说我要name而不设置每个子字段?

谢谢

1 个答案:

答案 0 :(得分:0)

问题是field:TYPE速记,不应将其与必需的选项字段混合使用。相反,我认为您可以尝试在此类父字段中不要使用速记:

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

或更明确:

{
  name: {
    type: { 
       first: { type: String},
       last: { type: String}
   },
   required: true
}
相关问题