1

I'm running into a trouble since a few days. I'm learning the MEAN stack, but during creation of a user on mongo using mongoose schema, I have this problem :

(node:93337) UnhandledPromiseRejectionWarning: ValidationError: User validation failed: username: Path username is required., password: Path password is required., email: Path email is required.

Here's my code :

The server part :

mongoose.connect('mongodb://localhost:27017/Wisebatt', err => {
  if (err) {
    console.log(`Not connected to db ${err}`)
  } else {
    console.log('Successfully connected to db')
  }
})

...

app.post('/register', (req, res) => {
    const user = new User();
    user.username = req.body.username;
    user.password = req.body.password;
    user.email = req.body.email;
    user.save();
    res.send('User created');
});

The UserSchema :

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

const UserSchema = new Schema({
    username: { type: String, required: true, unique: true},
    password: { type: String, required: true },
    email: { type: String, required: true, unique: true},
});

module.exports = mongoose.model('User', UserSchema);

Here are the add-ons I'm using :

  • Express,
  • Nodemon,
  • Morgan,
  • Body Parser,
  • Mongo (With mongod running & Mongoose)
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • can you post the part where you setup the database (mongodb) on the server? I'm guessing you haven't got the right credentials or database. – Matt Pengelly May 27 '18 at 01:53
  • Sure, here it is : ``mongoose.connect('mongodb://localhost:27017/Wisebatt', (err) => { if(err){ console.log(`Not connected to db ${err}`); } else { console.log('Successfully connected to db'); } });`` – Yanis Bendahmane May 27 '18 at 01:54
  • You're not setting a username/password to connect to MongoDB with your current DSN – Explosion Pills May 27 '18 at 01:57
  • can you console log req.body.username ? it might be undefined. – Matt Pengelly May 27 '18 at 01:57
  • `console.log(req.body)`. The error is from Mongoose validation of your schema. It means that there is no value assigned to the `username` or `password` fields. This is because they have been given `null` values because there is no such properties in `req.body`. You likely have something wrong with the request or body parser setup. Nothing to do with the connection. – Neil Lunn May 27 '18 at 01:58
  • clearly something is failing, not sure what because I'm not that familiar with mongoose - however, your code seems to be written as if `.save` is **synchronous** ... hint: it isn't, and that's where the unhandled rejection warning comes from – Jaromanda X May 27 '18 at 01:58
  • @ExplosionPills Yeah, I'm not setting any username/password, but It's supposed to work because I managed to send a post request with an empty object – Yanis Bendahmane May 27 '18 at 01:59
  • @MattPengelly Yeah it's undefined – Yanis Bendahmane May 27 '18 at 01:59
  • 1
    if `req.body` is undefined, then the problem could be (most likely) in the client code that you've failed to show - please show your client side code – Jaromanda X May 27 '18 at 02:14
  • seriously, you need to show your client side code as that is the likely place you've made one error (you still have an error in this code though, because you treat `.save` as being synchronous – Jaromanda X May 27 '18 at 02:23
  • By the client code, you mean the post request I sent to my server ? – Yanis Bendahmane May 27 '18 at 02:24
  • yes ... what is **sending** the `POST` request - that's the *client* to your *server* – Jaromanda X May 27 '18 at 02:25
  • @JaromandaX see the other comment thread. he mentioned using a REST client and we touched on that for a bit. Hes still having issues though im guessing its still related to the REST Client. – Matt Pengelly May 27 '18 at 02:25
  • that's irrelevant @MattPengelly, can't help fix his issue if he doesn't show the code that most likely has the issue – Jaromanda X May 27 '18 at 02:26
  • I'm sending the POST request with a firefox addon called RESTClient, I added the Content-Type Headers and the body request looks good for me : ``{ 'username': 'Hello', 'password': 'Nope', 'email': 'a@a.fr' }`` – Yanis Bendahmane May 27 '18 at 02:27
  • It's not irrelevant. It's just not particularly helpful because he can't easily show his request object. It's completely relevant. – Matt Pengelly May 27 '18 at 02:27
  • I meant the comment is irrelevant (in a way) because the OP needs to show the code in the **question** ... – Jaromanda X May 27 '18 at 02:28
  • @YanisBendahmane - in your browser, check the *developer* tools network tab, to see what the browser is sending in that `POST` request – Jaromanda X May 27 '18 at 02:28
  • and what code interprets `{ 'username': 'Hello', 'password': 'Nope', 'email': 'a@a.fr' }` as being a username, password and email? - that's just a string – Jaromanda X May 27 '18 at 02:30
  • Here's what's sent by my browser : `'email': '?' 'password': 'Hey', 'username': 'Oui', { }` – Yanis Bendahmane May 27 '18 at 02:32
  • And yeah... The two lasts are really weird – Yanis Bendahmane May 27 '18 at 02:32

4 Answers4

2

try adding this to your express code prior to your routes. This is a middleware that will setup the req.body object when you send requests to the backend. (you'll also need to npm install --save body-parser)

const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())

if youre using a rest client. make sure that you have a request header such as:

Content-Type: application/x-www-form-urlencoded
Matt Pengelly
  • 1,480
  • 2
  • 20
  • 34
1

Okay I found the problem...

Clearly, the problem is due to one of these two :

  • The browser used,
  • The extension sending the POST request

Surprise, I tried with Postman, and the request successfully work. So all the code was great, the problem came from one of the two up.

So, that learned me a thing. If it's not your code, It's the software you're using that can destroy all you have done

  • 2
    Did you end up using the Content-Type: application/x-www-form-urlencoded like i mentioned? because if so it'd be nice to get an upvote or marked as answer. Your answer here isn't really providing any information to the next user that has this problem – Matt Pengelly May 27 '18 at 03:12
  • Yeah, I added it, I will upvote, thanks for your help :) – Yanis Bendahmane May 27 '18 at 03:18
0

If you are using expressJS then make sure that you have to add this lines.

const express = require('express');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

Specially this one,

app.use(express.urlencoded({ extended: true }));

This actually solved my problem.

Chaitanya Bhojne
  • 156
  • 4
  • 10
0

Use:

app.use(express.urlencoded({ extended: true })); // this is for app.post to submit route.. 

in the app.js or index.js

kyun
  • 9,710
  • 9
  • 31
  • 66
Mohi007
  • 11
  • 2