Getting validation error in nodejs while sending data via post req

server js code

const express=require('express');
const app = new express();
app.use(express.json())// will convert string into obj
 const employeeRouter=require('../controller/employee-controller');
 app.use(employeeRouter);
require('../models/db')

const hbs=require('hbs');
const path=require('path');

const publicPath=path.join(__dirname,'../public');
app.use(express.static(publicPath));
const Employee=require('../models/employee-model');

const viewsPath=path.join(__dirname,"../views");
app.set('views',viewsPath);
app.set('view engine','hbs');
app.listen(8000,()=>{
    console.log("connect to server bro");
})

router file

const express=require('express');
const Employee=require('../models/employee-model');
const router=express.Router();
router.get('/',(req,res)=>{
    res.send("home page");
})
router.get('/add',(req,res)=>{
    res.render('index');
})
router.post('/employee',async(req,res)=>{
    const employee=new Employee()
    try{
        await employee.save();
        res.status(200).send("recorded successfully")
    }
    catch(err){
        res.status(404).send(err)
    }
    // console.log(req.body);
})
module.exports=router;

mongoose model

const mongoose=require('mongoose');
const validator=require('validator');
const employeeSchema=new mongoose.Schema({
    name:{
        type:String,
        required:true,
        trim:true
    },
    email:{
        type:String,
        required:true,
        trim:true,
        unique:true,
        validate(value){
            if(!validator.isEmail(value)){
                throw new Error ("Please enter correct email");
            }
        }
    },
    number:{
        type:Number,
        required:true,
        unique:true,
        validate(value){
            if(value.length!=10){
                throw new Error ("Please Enter 10 digit mobile number");
            }
        }
    },
    city:{
        type:String,
        required:true,
    }
})
const Employee=mongoose.model('employees',employeeSchema);
module.exports=Employee;

error while posting data

{
    "errors": {
        "city": {
            "name": "ValidatorError",
            "message": "Path `city` is required.",
            "properties": {
                "message": "Path `city` is required.",
                "type": "required",
                "path": "city"
            },
            "kind": "required",
            "path": "city"
        },
        "number": {
            "name": "ValidatorError",
            "message": "Path `number` is required.",
            "properties": {
                "message": "Path `number` is required.",
                "type": "required",
                "path": "number"
            },
            "kind": "required",
            "path": "number"
        },
        "email": {
            "name": "ValidatorError",
            "message": "Path `email` is required.",
            "properties": {
                "message": "Path `email` is required.",
                "type": "required",
                "path": "email"
            },
            "kind": "required",
            "path": "email"
        },
        "name": {
            "name": "ValidatorError",
            "message": "Path `name` is required.",
            "properties": {
                "message": "Path `name` is required.",
                "type": "required",
                "path": "name"
            },
            "kind": "required",
            "path": "name"
        }
    },
    "_message": "employees validation failed",
    "name": "ValidationError",
    "message": "employees validation failed: city: Path `city` is required., number: Path `number` is required., email: Path `email` is required., name: Path `name` is required."
}

data i am posting

{
    "name":"mahir jain",
    "email":"mahirjain@gmail.com",
    "number":1234567890,
    "city":"mumbai"
}

need serious help cause i am stuck at this issue past 15 days

I didn’t test your code, so I’m just guessing here…

I think maybe you need to provide the data to where you create the new Employee. You have:

router.post('/employee',async(req,res)=>{
    const employee=new Employee()

Maybe it needs to be something like:

router.post('/employee',async(req,res)=>{
   const { name, city, email, number } = req.body;
   const employee=new Employee({ name, city, email, number })
1 Like

Thanks it got solved … can you tell me difference between what you did and what I did I am asking because I am currently learning backend

Here’s what I saw - your third code block, “errors while posting data”, shows an error for each property. The name, email, etc. - none of them were valid. So it seemed like you weren’t providing any of them. I glanced at the rest of your code to see why it might not be getting any of the properties and saw the const employee=new Employee(). You were trying to create an employee without providing any of the required properties. The request was sending the data to the route, but you weren’t doing anything with the data. You need to get the data from the request body (req.body) and add it when creating the new Employee, like I showed.

You could add a console log in there to see what’s coming through to the route. e.g:

router.post('/employee',async(req,res)=>{
  console.log(req.body);

Perhaps that would have helped, or may help in the future.

okay sir but sorry to post this same problem in different code and the whole is right according to me but its not working

const express=require('express');
const app=new express();
app.use(express.json());
app.use(express.urlencoded({extended:true}));
const Task =require('../2-mongoose/4-task');
// const routers=require('../4-routers/task-router')// yeh rha ;
// app.use(routers);// yeh rha
app.post('/tasks',async(req,res)=>{// yeh kam kar rha hai
    const task=new Task(req.body);
    try{
        await task.save();
        console.log(req.body)
        res.status(201).send(task);
    }
    catch(err){
        res.status(404).send(err);
    }
})

//
app.listen(8000,()=>{
    console.log('server started broo');
})

Check the errors - find out what isn’t working.

const task=new Task(req.body);

The req.body may not be what new Task expects. Add that console log I shared and see what it contains. You probably need to get only the properties you need from it, or maybe add something to it.

thank you sir the error got solved .It was because I was sending json key completed instead of completion . again thank you so much

1 Like