从mongodb对象中选择返回undefined

时间:2017-05-02 11:15:30

标签: node.js mongodb express mongoose

我正在尝试构建一些auth,并且在成功验证后我无法访问mongodb中对象内的对象内的值,它返回undefined。关于mongodb对象有什么我需要知道的吗?

这是我的代码:

    app.post('/user/auth', function (req, res) {
  // find the user
  console.log('requested stuff 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
        });
      }

    }

  });
}); 

0 个答案:

没有答案