skip to Main Content

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

2

Answers


  1. You could try

    statusType: {
      type: Number,
      default: StatusType[StatusType.Approved],
      enum: Object.values(StatusType)
    }
    
    Login or Signup to reply.
  2. Typescript enums are really fuzzy and have a lot of issues, instead try using

    const StatusType = {
        Decline: 1,
        Approved: 0
    } as const;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search