我对使用Mongoose和MongoDB相当陌生。我正在注册/登录页面。 register函数可以正常工作,将用户帐户存储到数据库中,但是我的问题是登录。我想做的是从数据库中从匹配的用户那里获取'password'属性,以与密码匹配用户输入。这是我的登录功能。

router.post('/logSubmit', function(req, res, next) {
var gusername = req.body.username;
var gpassword = req.body.password;

User.count({
    'credentials.username': gusername
}, function(err, count) {
    if (err) throw err;
    console.log(count);
    if (count > 0) {

      // Where I need to pull password attribute from the database

    } else {

      // Wrong username or password

    }
});
});


我在互联网上四处寻找如何从数据库条目中读取属性,但找不到任何东西。我觉得这很简单,但是我想我不知道语法。我的模型的名称是User。我想这将是这样的:

User.find({ username: gusername }, function(err, user) {
if (err) throw err;

var getpassword = user.password;
console.log(getpassword);

});


我三思而后行,但没有成功。如何从数据库访问密码属性?谢谢。

编辑:

这是我的用户帐户存储在数据库中的样子:

{
"_id": {
    "$oid": "569e5344d4355010b63734b7"
},
"credentials": {
    "username": "testuser",
    "password": "password1234"
},
"__v": 0
}

最佳答案

find查询足以满足您的目的。如果从user查询中检索到非null find对象,则可以保证它是具有密码的用户。

User.find({ 'credentials.username': gusername }, function(err, users) {
  if (err) throw err;

  // 'users' is an array of the User objects retrieved.
  users.forEach(function(user) {
    // Do something with the password.
    // The password is stored in user.credentials.password
    console.log(user.credentials.password);
  });
});

关于node.js - 如何访问 Mongoose 架构属性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34884393/

10-11 21:02