0

I am trying to test my routes using the postman. The below is my user.model.js file

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const userSchema = new Schema({
  username: {
    type: String,
    required: true,
    unique: true,
    trim: true,
    minlength: 3
  },
}, {
  timestamps: true,
});

const User = mongoose.model('User', userSchema);

module.exports = User;

My router file for the user is below

const router = require('express').Router();
let User = require('../models/user.model');

router.route('/').get((req, res) => {
    User.find()
        .then(users => res.json(users))
        .catch(error => res.status(400).json('Error: ' + error));
});

router.route('/add').post((req, res) => {
    const username = req.body.username;

    const newUser = new User({ username });

    newUser.save()
        .then(() => res.json('User added!'))
        .catch(error => res.status(400).json('Error: ' + error));
});

module.exports = router;

each time when I am trying to test the post route for user I am getting "Error: ValidationError: username: Path username is required." error below is the screenshot of my postman enter image description here

Could anyone please help me in figuring out where I am wrong.

2
  • are you getting req.body.username in your router ? Nov 2, 2019 at 15:49
  • By adding header as below, it works. Click the Headers button in Postman and put value Content-Type application/json Oct 28, 2020 at 18:37

3 Answers 3

11

The data you passed should be in JSON format and not in multi-part format. Change your Postman request as following and check.

enter image description here

3

I had the same problem. I could solve the problem by adding the next parts in my program:

const bodyParser = require("body-parser");

app.use(bodyParser.urlencoded({ extended: false })); 
app.use(bodyParser.json());

My bodyparser version was "^1.15.2"

1
  • This was the solution for me. Was driving me nuts for the last couple of hours. Thanks!
    – mikeym
    Sep 9, 2022 at 19:31
2

Change your /add router:

const newUser = new User({ username : username }); // change

You have to pass your username this way.Hope this will help you.if you have any error though then let me know.

2
  • @Prakesh Karena if I will remove required property from username field then I am able to post my information to my route Nov 2, 2019 at 15:22
  • have you check your database store username or not? Nov 2, 2019 at 15:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.