简体   繁体   中英

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. 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

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

const StatusType = {
    Decline: 1,
    Approved: 0
} as const;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM