0

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",
    });
  }
};
1
  • What are the inferred types of title and campaign in const {title, campaign} = request.body? Commented Nov 4, 2024 at 13:41

1 Answer 1

1

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"
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.