//controller:
const Product = require("../models/productModel");
//Create product
exports.createProduct = async (req, res, next) => {
const product = await Product.create(req.body);
res.status(201).json({
success: true,
product,
});
};
productModel.js:
const mongoose = require("mongoose");
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,//err here.
},
})
There is an answer at link but those do not fix my error.
Here is the request that I send:
http://localhost:4000/api/v1/product/new (POST request with JSON content)
JSON:
{
"name":"Vaseline petrolatum Jelly"
}
The above code gives the below error:
this.$__.validationError = new ValidationError(this);
^
ValidationError: Product validation failed: name: Path name
is required.
at Document.invalidate (C:UsersDELLDownloadsreact-learnnode_modulesmongooselibdocument.js:3289:32)
at C:UsersDELLDownloadsreact-learnnode_modulesmongooselibdocument.js:3050:17
at C:UsersDELLDownloadsreact-learnnode_modulesmongooselibschemaType.js:1388:9
at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
errors: {
name: ValidatorError: Path name
is required.
at validate (C:UsersDELLDownloadsreact-learnnode_modulesmongooselibschemaType.js:1385:13)
at SchemaType.doValidate (C:UsersDELLDownloadsreact-learnnode_modulesmongooselibschemaType.js:1369:7)
at C:UsersDELLDownloadsreact-learnnode_modulesmongooselibdocument.js:3042:18
at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
properties: {
validator: [Function (anonymous)],
message: ‘Path name
is required.’,
type: ‘required’,
path: ‘name’,
fullPath: undefined,
value: undefined
},
kind: ‘required’,
path: ‘name’,
value: undefined,
reason: undefined,
[Symbol(mongoose#validatorError)]: true
}
},
_message: ‘Product validation failed’
}
I tried the solutions at link but none of them worked for me.
2
Answers
I used express.json() in app.js but it was down below another line:
The error message you’re encountering, "ValidationError: Product validation failed: name: Path name is required," indicates that Mongoose is not receiving the name field from the request body as expected.
In your Express app setup, ensure you have the following middleware to parse JSON request bodies:
Your controller and model code seem to be correct, but let’s add error handling to the controller to log the request body.
Make sure that your POST request to http://localhost:4000/api/v1/product/new is correctly formatted and contains the Content-Type: application/json header.
Example using curl: