我正在尝试从 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/