Search code examples
mongodbmongoosemongoose-schema

Error when using required field in schema in mongoose


//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:\Users\DELL\Downloads\react-learn\node_modules\mongoose\lib\document.js:3289:32) at C:\Users\DELL\Downloads\react-learn\node_modules\mongoose\lib\document.js:3050:17 at C:\Users\DELL\Downloads\react-learn\node_modules\mongoose\lib\schemaType.js:1388:9 at process.processTicksAndRejections (node:internal/process/task_queues:77:11) { errors: { name: ValidatorError: Path name is required. at validate (C:\Users\DELL\Downloads\react-learn\node_modules\mongoose\lib\schemaType.js:1385:13) at SchemaType.doValidate (C:\Users\DELL\Downloads\react-learn\node_modules\mongoose\lib\schemaType.js:1369:7) at C:\Users\DELL\Downloads\react-learn\node_modules\mongoose\lib\document.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.


Solution

  • 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;