Express validator检查名称是否在数据库中不存在以启用创建



我想要一个验证器来检查类别标题是否存在以启用类别的创建,但如果类别存在则禁止创建。我怎么检查呢?

这是我的模型:

const CategoryScheme = new mongoose.Schema({
title: {
type: String,
},
dishes: [{ type: mongoose.Types.ObjectId }],
timestamps: true,
versionKey: false,
});

您可以在中间件中这样做。

// 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()

最新更新