skip to Main Content

I would like to directly access the character enum array that exists in my model, from my controller, so that I don’t have to hard code the array in my controller. Is there an easy way to do this, or should I just store the array as a variable in my model and then export it along with the model?

testModel.js:

    const mongoose = require("mongoose");
    const testSchema = new mongoose.Schema({
      character: {
        type: String,
        enum: [
          "mario",
          "luigi",
          "link",
          "samus"
        ],
        required: [true, "Please provide a character"],
      },
    });

const Savestate = mongoose.model("Test", testSchema);
module.exports = Test;

controller.js

exports.getCharacterSavestates = catchAsync(async (req, res, next) => {

// Instead of this array I want to do something like: const characters = model.character.enum
  const characters = [
    "mario",
    "luigi",
    "link",
    "samus",
  ]; 

  if (!characters.includes(req.params.character)) {
    return next(new AppError("Character name invalid"), 400);
  }

  const documents = await Model.find({ character: req.params.character });
  res.status(200).json({
    status: "success",
    results: .length,
    data: { data: documents },
  });
});

2

Answers


  1. Use testSchema.paths.character.options.enum to retrieve that enum.

    Example:
    enter image description here

    Or you can have defined that enum array separated and use it on multiple places..

    Login or Signup to reply.
  2. you can use schema.path to retrive enum values

    const Model = require('./testmodel');
    
    exports.getCharacterSavestates = catchAsync(async (req, res, next) => {
    const characterEnum = Model.schema.path('character').enumValues; // us
    
    if (!characterEnum.includes(req.params.character)) {
    return next(new AppError("Character name invalid"), 400);
    }
    
    const documents = await Model.find({ character: req.params.character });
    res.status(200).json({
    status: "success",
    results: documents.length,
    data: { data: documents },
      });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search