Nodejs – 从MongoDB中检查空对象并parsing它
我试图从NodeJS(使用ExpressJS)和MongoDB实现一个简单的login机制。 我使用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) }) } }) }
我检查如果文档contanis空对象(这意味着用户名和密码不匹配),并告诉页面显示login无效。 如果文档确实包含匹配的用户名和密码,则使用console.log()
命名用户的名字。
上面的代码不工作…我做错了什么?
提前致谢…
我认为,而不是做你在做什么,如果你只是运行一个查询结果的限制一个用户名,看看返回的文档是否包含结果,会更有意义。 从那里我们将检查发布的密码是否匹配从数据库查询的密码,如果是这样,我们将console.log用户名。 此外,而不是查询密码,你应该首先哈希它。 阅读更多关于这里
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应用程序中的Angular.js特性
- Express中的服务器端validation与单页Angular应用程序兼容
- Azure AD – 检查安全组成员资格 – (Node.js,护照,Azure Web App)
- 在express.js中,req.files是未定义的
- ValidationException:ExpressionAttributeValues不能为空
- sequelize.js:未处理的拒绝SequelizeForeignKeyConstraintError
- MongoDB进入一个Express项目
- 数据不会从AngularJS控制器传递到NodeJS服务器
- node.js http获取请求参数