[英]Mongoose Schema enum and typescript enums
We have a Typescript based NodeJs project that makes use of Mongoose. We are trying to find an appropriate way to define an enum field on a Mongoose schema, based on a Typescript enum.我们有一个基于 Typescript 的 NodeJs 项目,它使用 Mongoose。我们正试图找到一种合适的方法来基于 Typescript 枚举在 Mongoose 架构上定义枚举字段。 Taking an example enum:
以枚举为例:
enum StatusType {
Approved = 1,
Decline = 0,
}
const userSchema = new Schema({
user: { type: Schema.Types.ObjectId, ref: 'User' },
statusType: {
type: Number,
default: StatusType.Approved,
enum: Object.values(StatusType)
}
});
But we keep getting a validation error but anytime we change the type of the statusType to但是我们不断收到验证错误,但每当我们将statusType的类型更改为
type: String
It works but it saves the status as a string like "0" instead of 0它有效,但它将状态保存为字符串,如“0”而不是0
You could try你可以试试
statusType: {
type: Number,
default: StatusType[StatusType.Approved],
enum: Object.values(StatusType)
}
Typescript enums are really fuzzy and have a lot of issues, instead try using Typescript 枚举真的很模糊并且有很多问题,请尝试使用
const StatusType = {
Decline: 1,
Approved: 0
} as const;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.