I want a validator to check if the category title does not exist to enable the creation of the category, but if the category exists then forbid the creation. How do I check that?
This is my model:
const CategoryScheme = new mongoose.Schema({
title: {
type: String,
},
dishes: [{ type: mongoose.Types.ObjectId }],
timestamps: true,
versionKey: false,
});
CodePudding user response:
You can do something like this in your middleware.
// if you are passing the category in req.body
const { title } = req.body
const category = await CategoryModel.findOne({title})
// This checks if there exists a category with the given title
if(category){
// Return a response if the category is present
return res.status(400).send({message: 'Category already taken!'}
}
next()