【问题标题】:One of several values as a type in Mongoose (union type)作为 Mongoose 类型的几个值之一(联合类型)
【发布时间】:2023-02-26 00:37:10
【问题描述】:

我正在尝试制作一个用于注册的 API,用户需要在其中输入他们的性别:“男”或“女”。我试过这个:

{
  gender: {
    type: "male" | "female"
    required: true
  }
}

但这不起作用。我搜索了解决方案,但没有找到解决方案。有没有办法像这样定义类型,或者应该在服务器上检查值?

【问题讨论】:

  • "male" | "female" 的计算结果为 0。好像你想要一个枚举.

标签: mongodb mongoose


【解决方案1】:

你可以在猫鼬中使用enum。是这样的:

gender: {
   type: String,
   enum : ["male","female"],
   required: true
},

请记住,这里的 type 将是 String,值将是“男性”或“女性”,它不会像其他 enums 那样表现,例如在 TypeScript 等中。

【讨论】:

    猜你喜欢
    • 2021-12-30
    • 2023-03-06
    • 2019-05-10
    • 2021-06-13
    • 2019-01-12
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 2020-10-26
    相关资源
    最近更新 更多