Home > Back-end >  ValidationError: planModel validation failed: price: Path `price` is required,duration: Path `durati
ValidationError: planModel validation failed: price: Path `price` is required,duration: Path `durati

Time:02-01

` As I am trying to save the data through the Postman into the MongoDb with Mongoose(by keeping all data in perfect,Body>raw>json).But, I am Still getting the ValidationError...

I have tried previous Solution on this platform but got no solution that's why I am posting it,please anyone resolve it.I am trying it by three days to resolve.

This is How I created UserSchema :-

const Planschema = mongoose.Schema({

name:{
    type:String,
    required:true,
    maxlength:20
},


duration:{
    type:Number,
    required:true
}


,price:{
 type:Number,
 required:true
},


 ratingAverage:{
     type:Number
 },


discount:{
 type:Number,
 validate:function(){
    return this.discount<100;
 }
}

})

This is the way I am trying to Save the data:-

module.exports.createPlan= async function createPlan(req,res){ let data = req.body;

// First I have tried this Way

// let createData = await planModel.create(data);

// After failing to save that way I used this way too.

let doc = new planModel(data);

let userdetails= await doc.save(); res.json({ message:"Data has been Created", data:userdetails })

}

`

CodePudding user response:

I think you should check if your body is defined or not. If not, ensure that the bodyParser at the root of your project is implemented : Considering the last version of express, you could do :

app.use(express.json());

Or use the body-parser package : https://www.npmjs.com/package/body-parser

const bodyParser = require('body-parser');
app.use(bodyParser.json());
  • Related