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. 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
type: String
It works but it saves the status as a string like "0" instead of 0
CodePudding user response:
You could try
statusType: {
type: Number,
default: StatusType[StatusType.Approved],
enum: Object.values(StatusType)
}
CodePudding user response:
Typescript enums are really fuzzy and have a lot of issues, instead try using
const StatusType = {
Decline: 1,
Approved: 0
} as const;