2

I started the implementation of a RESTful API usin node.js, express, and mongodb. Everything went well until now, I've a route to authenticate an user as follow:

apiRoutes.post('/authenticate', function(req, res) {
    User.findOne({
        nickname: req.body.nickname
    }, function(err, user) {

        if (err) throw err;

        if (!user) {
            res.json({
                success: false,
                message: 'Authentication failed. User not found.'
            });
        } else if (user) {
            console.log(user);
            console.log(user.nickname);
            console.log(user.email);
            console.log(user.password);
            console.log(user.sexe);

            if (user.password != req.body.password) {
                res.json({
                    success: false,
                    message: 'Authentication failed. Wrong password.'
                });
            } else {
                var token = jwt.sign(user, app.get('salt'), {
                    expiresInMinutes: 1440 // expires in 24 hours
                });

                res.json({
                    success: true,
                    token: token
                });
            }
        }
    });
});

The user is retrieved, and loged in the console as follow:

{ sexe: 'H',
  email: '[email protected]',
  password: 'bambou',
  nickname: 'MrPanda',
  _id: 56cb703e7aef3f83c7dac0a7 }

which is perfect, but then, the three following consol.log return the three following lines:

MrPanda
[email protected]
undefined
H

I see absolutely no reason why the password is undefined at this point, I tried to change the attribute name to 'mdp', same issue... Any ideas ? Thanks

1
  • Try to copy user.password to new variable and log it. Feb 22, 2016 at 20:52

1 Answer 1

4

If you are using mongoose it does not return a plain JSON object. It is actually a special mongoose object and may not function how you expect.

You have two options:

  1. Convert the mongoose object to a JSON object.

    • Add {lean: true} to the Users options parameter.
    • OR JSON.stringify(user)
    • OR user.toJSON()
  2. Use the proper get() and set() methods (which you should be doing anyways).

    • user.get('password')
    • user.get('email')
    • user.get('name')

Try that and let me know if it doesn't work still.

1
  • 1
    Thanks, was working on it for hours, but how come that I can get all the values, except for one? (which was an image URL) Aug 25, 2021 at 16:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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