如何访问Mongoose Schema属性?

时间:2016-01-19 18:31:54

标签: node.js mongodb

我使用Mongoose和MongoDB相当新。我正在注册/登录页面。注册功能工作正常,将用户帐户存储到数据库中,但我的问题是登录。我想要做的是从匹配的用户获取数据库的'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
}

1 个答案:

答案 0 :(得分:0)

find查询足以满足您的目的。如果从user查询中检索到非空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);
  });
});