8SINS
8SINS

Reputation: 461

How to solve Mongoose Error on Validation

I am building an API that allows the user to log certain data into the database(MongoDB) The problem is I keep getting the following errors:

UnhandledPromiseRejectionWarning: ValidationError: item validation failed: productName: Path `productName` is required.

here is my schema :

const mongoose= require('mongoose');
const Schema = mongoose.Schema;

//create Schema
const ItemSchema = new Schema({

   productName : {
       type : String,
       required:true
   } ,
   description : {
       type :String,
       default:true
   },
   supplier : {
       type :String,
       default:true
   },
   price : {
       type :Number,
       default:true
   },
   date : {
       type :Date,
       default:Date.now
   }
});

module.exports=Inventory=mongoose.model('item',ItemSchema,'inventory');

Here is the submit post route:

const express= require('express');
const router = express.Router();

//Items model
const Inventory = require('../../../models/Inventory');


router.post('/',(req,res)=>{

    const newInventory= new Inventory({
        productName:req.body.productName,
        description:req.body.description,
        supplier:req.body.supplier,
        price:req.body.price,
    });
       newInventory.save().then(item=>res.json(item))
   });


I can't figure out why it's throwing a validation Error!

Upvotes: 0

Views: 152

Answers (1)

8SINS
8SINS

Reputation: 461

This was the step I took to resolve the problem

first, i checked what i was getting from my req.body

const express= require('express');
const router = express.Router();

//Items model
const Inventory = require('../../../models/Inventory');
console.log(req.body) //checking for content of req.body

router.post('/',(req,res)=>{

    const newInventory= new Inventory({
        productName:req.body.productName,
        description:req.body.description,
        supplier:req.body.supplier,
        price:req.body.price,
    });
       newInventory.save().then(item=>res.json(item))
   });

I got an empty object { }, this means I wasn't getting any request in the first place. Testing with Postman, I changed the option from "form data" to :

 x-www-form-urlencoded

this filled my req.body with data and the error disappeared !

Upvotes: 1

Related Questions