I am trying to create product using nodejs and mongodb through my api for ecommerce management inventory but getting error as validation, the following below are my code that I have used.
This is my mongoose.js code
// require the library
const mongoose = require('mongoose');
require('dotenv').config();
// connecting database
mongoose.connect(process.env.MONGO_CONNECT);
// aquire the connection
const db = mongoose.connection;
//on error
db.on('error', console.error.bind(console, 'error connecting to db'));
// on success
db.once('open', function(){
console.log('Successfully connected to the database');
})
// exporting db
module.exports = db;
this is my schema
const mongoose = require('mongoose');
// Schema for Product [fields: id, name, quantity] with timeStamps
const productSchema = new mongoose.Schema({
name:{
type: String,
required: true
} ,
quantity:{
type: Number,
required: true
}
},{timestamps:true})
const Product = mongoose.model('Product', productSchema);
// exporting schema
module.exports = Product;
this is my controllerproduct js file
const Product = require('../models/product');
// Fetch List of products
module.exports.list = async function(req, res){
try{
let product = await Product.find()
return res.status(200).json({
data:{
message: "Products",
products: product
}
})
}catch(err){
console.log('Error in fetching List of products',err);
return res.send('Error in fetching List of products' err);
}
}
// Create Product
module.exports.create = async function(req, res){
try{
let product = new Product({
name: req.body.name,
quantity: req.body.quantity,
});
await product.save()
return res.status(200).json({
data:{
message: "Product created",
products: product
}
})
}catch(err){
console.log('Error in creating product',err);
return res.send('Error in creating product' err);
}
}
// Delete Product
module.exports.delete = async function(req, res){
try{
let product= await Product.findById(req.params.id);
await product.remove();
return res.status(200).json({
data:{
message: "Product removed from list",
}
})
}catch(err){
console.log('Error in removing product',err);
return res.send('Error in removing product' err);
}
}
// Update quantity
module.exports.update = async function(req, res){
try{
let product= await Product.findById(req.params.id);
// Here using req.query to update quantity [NOTICE: using number for query]
let num = parseInt(req.query.number);
if(product.quantity num < 0){
return res.status(200).json({
data:{
message: "Try Again! Product quantity could not be less then 0",
}
})
}else{
product.quantity = product.quantity num
await product.save()
return res.status(200).json({
data:{
message: "Product Quantity updated successfully",
products: product
}
})
}
}catch(err){
console.log('Error in updating quantity of the product',err);
return res.send('Error in updating quantity of the product:::' err);
}
}
module.exports.home = async function(req, res){
try {
return await res.send('Hello Admin')
} catch (error) {
console.log('Error at home',err);
return res.send('Error at home page:' err);
}
}
this is main index.js file
const express = require('express');
const port = process.env.PORT||8800;
const app = express();
const db = require('./config/mongoose');
// To parse incoming requests
app.use(express.urlencoded());
// It parses incoming requests with JSON
app.use(express.json())
// making connection to index of route
app.use('/', require('./routes/index'))
// connecting to port
app.listen(port, function(err){
if(err){
console.log(`Error! connecting Port : ${err}`);
}
console.log(`Connected on Port : ${port}`);
})
I'm trying to create product through my Api using postman but I am getting this error, any help will be appreciated:
Aditya Kumar@DESKTOP-980JOV2 MINGW64 ~/nodews/ecommerce-Api
$ node index.js
body-parser deprecated undefined extended: provide extended option index.js:7:17
Connected on Port : 8800
Successfully connected to the database
Error in creating product Error: Product validation failed: name: Path `name` is required., quantity: Path `quantity` is required.
at ValidationError.inspect (C:\Users\Aditya Kumar\nodews\ecommerce-Api\node_modules\mongoose\lib\error\validation.js:49:26)
at formatValue (node:internal/util/inspect:782:19)
at inspect (node:internal/util/inspect:347:10)
at formatWithOptionsInternal (node:internal/util/inspect:2167:40)
at formatWithOptions (node:internal/util/inspect:2029:10)
at console.value (node:internal/console/constructor:324:14)
at console.log (node:internal/console/constructor:360:61)
at module.exports.create (C:\Users\Aditya Kumar\nodews\ecommerce-Api\controllers\product_controller.js:34:17)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
errors: {
name: ValidatorError: Path `name` is required.
at validate (C:\Users\Aditya Kumar\nodews\ecommerce-Api\node_modules\mongoose\lib\schematype.js:1346:13)
at SchemaString.SchemaType.doValidate (C:\Users\Aditya Kumar\nodews\ecommerce-Api\node_modules\mongoose\lib\schematype.js:1330:7)
at C:\Users\Aditya Kumar\nodews\ecommerce-Api\node_modules\mongoose\lib\document.js:2835:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: [Object],
kind: 'required',
path: 'name',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
},
quantity: ValidatorError: Path `quantity` is required.
at validate (C:\Users\Aditya Kumar\nodews\ecommerce-Api\node_modules\mongoose\lib\schematype.js:1346:13)
at SchemaNumber.SchemaType.doValidate (C:\Users\Aditya Kumar\nodews\ecommerce-Api\node_modules\mongoose\lib\schematype.js:1330:7)
at C:\Users\Aditya Kumar\nodews\ecommerce-Api\node_modules\mongoose\lib\document.js:2835:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: [Object],
kind: 'required',
path: 'quantity',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'Product validation failed'
}
CodePudding user response:
It might be due to a miss config of an HTTP request header, please make sure you are sending a valid JSON payload when calling the API by adding a application/json
content-type header
Examples:
CURL
curl -X POST http://localhost:8000 -d '{"name": "Dummy", "quantity": 1}' -H "Content-Type: application/json"
Fetch
const res = await fetch('http://localhost:8000', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
});
CodePudding user response:
req.body.name
is most likely coming up as undefined
. try logging it out to the console, if it is indeed undefined
, then it may be due to some system error. you can try restarting your server or even your local machine.
the problem may also be from the request you are sending in postman. make sure that all the parameters are in the right place