'UnhandledPromiseRejectionWarning: ValidationError While inserting data
I'm following a MERN toturial on building a ecommerce website. I'm having UnhandledPromiseRejectionWarning: ValidationError this error occurs when I try to insert data into database using postman and I,m not able to warp my head arount it.
Here's the Error
(node:4864) UnhandledPromiseRejectionWarning: ValidationError: Product validation failed: category: Please enter product category, price: Please enter product price, description: Please enter product description, name: Please enter product name at model.Document.invalidate (D:\Project\ecommerce\node_modules\mongoose\lib\document.js:2907:32) at D:\Project\ecommerce\node_modules\mongoose\lib\document.js:2698:17 at D:\Project\ecommerce\node_modules\mongoose\lib\schematype.js:1280:9 at processTicksAndRejections (internal/process/task_queues.js:77:11)
This is the database connection file
const mongoose = require("mongoose");
const connectDatabase = () =>{
mongoose.connect(process.env.DB_URI).then((data)=>{
console.log(`Mongodb connected with server ${data.connection.host}`);
}).catch((err)=>{
console.log(err);
})
}
module.exports = connectDatabase;
This is the schema
const mongoose = require("mongoose");
const productSchema = new mongoose.Schema({
name:{
type:String,
required:[true, "Please enter product name"],
trim:true,
},
description:{
type:String,
required:[true, "Please enter product description"],
},
price:{
type:Number,
required:[true, "Please enter product price"],
maxLength:[7,"Price cannot exceed 7 characters"],
},
rating:{
type:Number,
default:0,
},
images:[
{
public_id:{
type:String,
required:true,
},
url:{
type:String,
required:true,
}
}
],
category:{
type:String,
required:[true, "Please enter product category"],
},
stock:{
type:Number,
required:[true, "Please enter product Stock"],
maxlength:[4, "Stock cannot exceed 4 characters"],
default:1,
},
numberOfReviews:{
type:Number,
default:0,
},
reviews:[
{
name:{
type:String,
required:true,
},
rating:{
type:Number,
required:true,
},
comment:{
type:String,
required:true,
}
}
],
createdAt:{
type:Date,
default:Date.now,
}
})
module.exports = mongoose.model("Product", productSchema);
This is the json file that I send through POST and the postman kept stuck on sending request.
"name":"product1",
"price":12000,
"description":"this is a sample product",
"category":"Laptop",
"images":{
"public_id":"sample Image",
"url":"sampleurl"
}
Solution 1:[1]
Your data is not in JSON format.In postman send data like this:
{
"name":"product1",
"price":12000,
"description":"this is a sample product",
"category":"Laptop",
"images":{
"public_id":"sample Image",
"url":"sampleurl"
}
}
Solution 2:[2]
Send data as JSON not as text type in postman.

Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | manzt |
| Solution 2 | 4b0 |
