I am working with this RESTful api and I want to send a post request to the server to create a document in the database. For that I am using model.create method. But it keeps me sending the error in the console
UnhandledPromiseRejectionWarning: ValidationError: Product validation failed: seller: Please enter product seller, category: Please enter the product category, description: Please enter product description, name: Please enter product name
I am testing this inside postman.
Is there any bugs in my code? How can I fix this.
Here is my app.js file
const express = require('express')
const mongoose = require('mongoose')
const bodyParser = require("body-parser");
const app = express()
app.use(bodyParser.urlencoded({extended: true}));
mongoose.connect('mongodb://localhost:27017/playDB', {useNewUrlParser: true, useUnifiedTopology: true})
const playSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Please enter product name'],
},
price : {
type: Number,
required: [true, 'Please enter product price'],
},
description: {
type: String,
required: [true, 'Please enter product description']
},
category: {
type: String,
required: [true, 'Please enter the product category'],
},
seller: {
type: String,
required: [true, 'Please enter product seller']
},
stock: {
type: Number,
required: [true, 'Please enter product stock'],
}
})
const Product = mongoose.model('Product', playSchema)
//get all products
app.route("/products")
.post(async function(req, res, next){
const product = await Product.create(req.body);
res.send({
success: true,
product
})
})
app.listen(3000, function(){
console.log('server is running')
})
CodePudding user response:
I didn't made express read express format. So that's why it didn't work
All I had to add was app.use(express.json())
Then it worked