skip to Main Content

//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


  1. Chosen as BEST ANSWER

    I used express.json() in app.js but it was down below another line:

    const express = require("express");
    const app = express();
    app.use(express.json());
    const product = require("./routes/productRoute");
    app.use("/api/v1", product);
    //it was previously here somewhere.
    module.exports = app;
    

  2. 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.

    1. Ensure Body Parsing Middleware is Used:
      In your Express app setup, ensure you have the following middleware to parse JSON request bodies:
    const express = require('express');
    const app = express();
    app.use(express.json()); // To parse JSON bodies
    
    1. Check the Controller and Model Code:
      Your controller and model code seem to be correct, but let’s add error handling to the controller to log the request body.
    const Product = require("../models/productModel");
    
    exports.createProduct = async (req, res, next) => {
      try {
        console.log('Request Body:', req.body); // Log the request body for debugging
        const product = await Product.create(req.body);
    
        res.status(201).json({
          success: true,
          product,
        });
      } catch (error) {
        console.error('Error creating product:', error);
        res.status(400).json({
          success: false,
          message: error.message,
        });
      }
    };
    
    1. Verify Request:
      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:

    curl -X POST http://localhost:4000/api/v1/product/new 
    -H "Content-Type: application/json" 
    -d '{"name": "Vaseline petrolatum Jelly"}'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search