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
Use testSchema.paths.character.options.enum to retrieve that enum.
Example:
Or you can have defined that enum array separated and use it on multiple places..
you can use schema.path to retrive enum values