typescriptmongoosemongoose-schema

How to use enum with values in Typescript?


Note: I'm a beginner level person in typescript, so, instead of downvoting my question, please try to elaborate the concept.

I'm having trouble using enum in my code. I want to use an enum(with values) and send only the key in the enum as campaign but I see the error:

"error": "Appeal validation failed: campaign: `\"HA\"` is not a valid enum value for path `campaign`."

Also tried changing the model to enum: Object.keys(Campaign),, but didn't work.

appealTypes.ts:

export enum Campaign {
  E = "Eid",
  R = "Ramadan",
  HA = "Hunger Appeal"
}

export interface Appeal {
  _id: string;
  title: string;
  campaign: Campaign;
}

appealModel.ts:

const appealSchema = new mongoose.Schema<Appeal>(
  {
    title: {
      type: String,
      required: true,
    },
    campaign: {
      type: String,
      enum: Object.values(Campaign),
      // required: true,
    },
  },
  { timestamps: true }
);

appealController.ts:

const createAppeal = async (request: Request, response: Response) => {
  try {
    const { title, campaign} = request.body;

    const newAppeal = await appealModel.create({
      title, campaign
    });

    response.status(201).json({
      message: "Appeal created successfully",
      data: newAppeal,
    });
  } catch (error) {
    console.error("Error creating appeal:", error);
    response.status(500).json({
      message: "Error creating appeal",
      error: error instanceof Error ? error.message : "Unknown error",
    });
  }
};

Solution

  • update mongoose schema to accept keys

    import mongoose from 'mongoose';
    
    enum Campaign {
      E = 'E',
      R = 'R',
      HA = 'HA',
    }
    
    const appealSchema = new mongoose.Schema<Appeal>(
      {
        title: {
          type: String,
          required: true,
        },
        campaign: {
          type: String,
          enum: Object.keys(Campaign), // Accepting keys like "E", "R", and "HA"
          required: true,
        },
      },
      { timestamps: true }
    );
    

    and create a new appeal like this:

    const newAppeal = await appealModel.create({
      title,
      campaign // This should be a key like "E", "R", or "HA"
    });