node.js - Nodejs - 检查 MongoDB 中的空对象并解析它

标签 node.js mongodb express authentication mongojs

我正在尝试从 NodeJS(使用 ExpressJS)和 MongoDB 实现一个简单的登录机制。我使用 MongoJS 进行数据库连接。我正在使用 $and: 来查看集合中的字段是否匹配。

function authenticate(req,res){

username  = req.body.username;
password = req.body.password;
db.users.find({$and :[{username:username},{password:password}]},function(err,doc){

   if(( Object.keys(doc).length === 0 && doc.constructor === Object) === false){
       res.send("Invalid login")
   } else {
       doc.forEach(function(doc){
           console.log(doc.firstname)
       })

   }
})
}

我检查文档是否包含空对象(这意味着用户名和密码不匹配)并告诉页面显示登录无效。如果文档确实包含匹配的用户名和密码,我将使用 console.log() 获取用户的名字...

上面的代码不起作用...我做错了什么?

提前致谢...

最佳答案

我认为,如果您只是简单地运行一个限制为一个结果的用户名查询并查看返回的文档是否包含结果,而不是做您正在做的事情,那么会更有意义。从那里我们将检查发布的密码是否与从数据库中查询的密码匹配,如果是,我们将 console.log 用户名。此外,您应该首先对密码进行哈希处理,而不是查询密码。了解更多相关信息 HERE

function authenticate(req,res){
    username  = req.body.username;
    password = req.body.password;
    db.users.findOne({"username":username}, function(err, doc) {
        if (err) throw err;
        if(doc && doc._id){
            if(password==doc["password"]){
                console.log("Your first name is: "+doc.firstname)
            }else{
                res.send("Invalid login")
            }
        }else{
            res.send("Invalid login")
        }
    });
}

关于node.js - Nodejs - 检查 MongoDB 中的空对象并解析它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42264487/

相关文章:

node.js - Ionic2 安装后的 Ionic 安装

node.js - 未处理的拒绝 MongoError : The dollar ($) prefixed field '$inc' in '$inc' is not valid for storage

javascript - 使用 Google Feed API 和 Node.js 订阅 RSS feed

javascript - 回调不是 mongoose.find({}) 中的函数

Node.js服务器使用Express.js上传文件名

javascript - 如何在node.js和express上的Restful API中设置编码UTF-8或WINDOWS_CP_1251

node.js - 使用 nodemailer 发送邮件 - 来自字段的电子邮件不正确

node.js - 有没有办法在 mongodb(mongoose) 的单个查询中创建 "stored procedure"调用多查询

node.js - Sequelize : Is it possible to return custom field names instead of regular field names?

linux - 为什么 npm 在我的主目录中创建一个名为 '~' 的文件夹?