'getting validation error while sending data via post request

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

my routes 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;

my server file

    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 viewsPath=path.join(__dirname,"../views");
app.set('views',viewsPath);
app.set('view engine','hbs');

app.listen(8000,()=>{
    console.log("connect to server bro");
})

sending json

   {
    "name":"mahir jain",
    "email":"[email protected]",
    "number":1234567890,
    "city":"mumbai"
}

error

    {
  "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."
}

**My sir helped me by shifting two lines above in server file and that worked but now its not working.The error is not because I am sending data which is invalid but its something else . please try to point out my mistake because I am facing this error in one more server file and I can give access to anydesk if someone is ready to help **



Solution 1:[1]

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);
})

The code above is thee issue. You are calling new Employee() and saving it without actually giving it parameters. Data passed to the router doesn't automatically get passed to the constructor. You need to first access the data from the request, then saving it.

const {name, email, number, city} = req.body
const employee = new Employee({name: name, email: email, number: number, city: city});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MTN