Why Mongoose doesn't validate on update?

后端 未结 6 2589
故里飘歌
故里飘歌 2020-11-30 00:07

I have this code

var ClientSchema = new Schema({
  name: {type: String, required: true, trim: true}
});

var Client = mongoose.mode(\'Client\', ClientSchema)         


        
6条回答
  •  孤城傲影
    2020-11-30 00:52

    In your model, ex. Category.js file:

    const CategorySchema = mongoose.Schema({
    category_name : {
    type : String,
    required : [true, 'Category Name Is Required !'],
    trim : true,
    maxlength : [30, 'Category Name Is To Long !'],
    unique : true,
    });
    const Category = module.exports = mongoose.model("Category",CategorySchema);
    

    In your route file:

    router.put("/",(req,res,next)=>{
      Category.findOneAndUpdate(
      {_id : req.body.categoryId},
      {$set : {category_name : req.body.category_name} },
      **{runValidators: true}**, function(err,result) {
        if(err){
          if(err.code === 11000){
           var duplicateValue = err.message.match(/".*"/);
           res.status(200).json({"defaultError":duplicateValue[0]+" Is Already Exsist !"});
           }else{
             res.status(200).json({"error":err.message} || {"defaultError":'Error But Not Understood !'});
           }
        }else{
         console.log("From category.js (Route File) = "+result);
         res.status(200).json({"success":"Category Updated Successfully!!"});
        }
    });
    

提交回复
热议问题