简体   繁体   中英

How to fix " Path is required ,ValidationError " ,Mongoose ,node

I have searched everywhere for this problem. but I cant find the correct way to fix it. help me to what is the problem.

    const router = require("express").Router();
    let Reg = require("../models/Register");

    http://localhost:8070/Register/add

  router.route("/add").post((req,res)=>{

const name = req.body.Name;
const email = req.body.Email;
const number = Number(req.body.Number);
const password = req.body.Password;


const NewAdd = new Reg({
    name,
    email,
    number,
    password

})

NewAdd.save().then(()=>{
    res.json("Registration Added")
}).catch((err)=>{
    console.log(err);
    res.json(err)
    console.log("reg err");
})



 })

and this is a module folder js

 const mongoose = require('mongoose');

 const Schema = mongoose.Schema;

 const RegSchema = new Schema({

Name: {
    type: String,
    required: true

},
Email: {
    type: String,
    required: true

},
Password: {
    type: String,
    required: true

},
Number: {
    type: Number,
    required: true

}

    });

     const Register = mongoose.model("Register",RegSchema);

      module.exports = Register;

This is server.js

    const express = require("express");
const mongoose = require("mongoose");
const bodyParser =require("body-parser");
const cors = require("cors");
 require("dotenv").config();
const app = express();

const PORT = process.env.PORT || 8070;

app.use(cors());
app.use(bodyParser.json());


const URL = process.env.MONGODB_URL;

mongoose.connect(URL,{
    useCreateIndex: true,
    useNewUrlParser: true,
    useUnifiedTopologyL: true,
    useFindAndModify: false
});

const connection = mongoose.connection;
connection.once("open", () =>{
    console.log("Mongodb connection success!");
})


const AddRouter = require("./routes/Registers.js");


app.use("/Register",AddRouter);



app.listen(PORT, () =>{
    console.log(`The port is : ${PORT}`);
})

error showing

Name: ValidatorError: Path Name is required. at validate (C:\Users\Sliit\Desktop\Reg-Backend\Travel-management-system\node_modules\mongoose\lib\schematype.js:1270:13) at C:\Users\Sliit\Desktop\Reg-Backend\Travel-management-system\node_modules\mongoose\lib\schematype.js:1253:7 at Array.forEach () at SchemaString.SchemaType.doValidate (C:\Users\Sliit\Desktop\Reg-Backend\Travel-management-system\node_modules\mongoose\lib\schematype.js:1198:14) at C:\Users\Sliit\Desktop\Reg-Backend\Travel-management-system\node_modules\mongoose\lib\document.js:2545:18 at processTicksAndRejections (node:internal/process/task_queues:78:11) { properties: [Object], kind: 'required', path: 'Name', value: undefined, reason: undefined, [Symbol(mongoose:validatorError)]: true } }, _message: 'Register validation failed' }

I testing API from the postman and get this error

"errors": { "Number": { "name": "ValidatorError", "message": "Path Number is required.", "properties": { "message": "Path Number is required.", "type": "required", "path": "Number" }, "kind": "required", "path": "Number" }, "Password": { "name": "ValidatorError", "message": "Path Password is required.", "properties": { "message": "Path Password is required.", "type": "required", "path": "Password" }, "kind": "required", "path": "Password" }, "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": "Register validation failed", "name": "ValidationError", "message": "Register validation failed: Number: Path Number is required., Password: Path Password is required., Email: Path Email is required., Name: Path Name is required." }

Use the same case in "NewAdd" and in "RegSchema".

const NewAdd = new Reg({
  name,
  email,
  number,
  password
})

and

const RegSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  number: {
    type: Number,
    required: true
  }
})

I was facing the same issue. I have changed my schema while my server is running. I just restart the server and error is gone. If you also changed your schema while your server is still running try to restart your server.

Follow up and need to check this all point

1. add app.use(express.json()) in app.js file
2. use req.body for storing a data in mongodb.
eg app.post('/student',(req,res)=>{
   const user= new Student({
       name:req.body.name,
       email:req.body.email,
number:req.body.number,
message:req.body.message
   })
user.save().then(()=>{
res.status(201).send(user)
}).catch((e)=>{
res.status(400).send(e)
})
  1. select JSON option on dropdown of postman 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM