Tuesday, 2 May 2017

Selecting from mongodb object returns undefined

I'm trying to build some auth and after successful auth I can't access values inside object inside object in mongodb, it returns undefined. Is there any thing I need to know about mongodb objects?

Here's my code:

    app.post('/user/auth', function (req, res) {
  // find the user
  console.log('requested shit is ' + req.body.username + ' and ' + req.body.password)
  User.find({
    'data.username': req.body.username,
    'data.password': req.body.password
  }, function (err, user) {
    console.log(user) // returns { _id: 59085883734d1d3098a83590, data: { username: 'admin1', password: 'password', email: 'email' }, profile: { nickname: 'workingNickname' } }
    console.log(user.data) // returns undefined
    console.log(user['data']) // returns undefined
    if (err) throw err;
    if (!user) {
      res.send('User not found with' + req.body.username);
    } else if (user) {
      // check if password matches
      if (user.password != req.body.password) {
        res.send('Password wrong. Auth failed');
      } else {

        // if user is found and password is right
        // create a token
        var token = jwt.sign(user, app.get('superSecret'), {
          expiresIn: 60 * 60 * 24 // expires in 24 hours
        });
        // return the information including token as JSON
        res.json({
          success: true,
          message: 'Enjoy your token!',
          token: token
        });
      }

    }

  });
}); 



via zaebalo

No comments:

Post a Comment