【发布时间】:2016-07-06 14:12:57
【问题描述】:
我是 Node Express Mongo 的新手,所以在学习了一些教程之后,我想尝试重写我自己的婴儿网站。这是login 页面。其他人的代码对我有用,但是当我尝试时,我的方法不起作用。我还查阅了文档,他们做了类似db.bios.find( { _id: 5 } ) 之类的东西,这是我试图模仿的
db 是ShipDB,集合是users,我要查找的文档是
{
"_id" : ObjectId("56edc18064e429581541808a"),
"username" : "username",
"password" : "password"
}
下面,我正在连接,如果 result.length 则重定向到主页。我尝试在网站上正确输入username 和password,但显示登录无效。 console.log(result.length) 打印出未定义?这是为什么?这是logcat:
Connection established successfully
undefined
{ username: 'username', password: 'password' }
router.post('/validate', function(req, res) {
var MongoClient = mongodb.MongoClient;
var url = "mongodb://localhost:27017/"+database_name;
MongoClient.connect(url, function(err, db) {
if(!err) {
console.log("Connection established successfully");
var user_collection = db.collection(collection_name_users);
var user_login_input = {
username: req.body.username,
password: req.body.password
};
// THIS IS THE FUNCTION THAT I HAVE A PROBLEM WITH!!!!
user_collection.find(
{
username: req.body.username,
password: req.body.password
}, function(err, result) {
if(!err) {
console.log(result.length);
if (result.length) {
// Successful login
req.session.user = result;
delete req.session.user.password;
res.redirect("home");
} else {
console.log(user_login_input);
res.send("Invalid login");
}
db.close();
} else {
console.log(err);
}
});
} else {
console.log("Cannot connect ", err);
}
});
});
我尝试过的事情:
user_collection.find(user_login_input, function(err, result) {...user_collection.find({ "username": req.body.username, "password": req.body.password })...在 mongoshell 上工作:
感谢您的宝贵时间。
编辑:findOne 看起来已弃用
【问题讨论】:
-
@JohnnyHK 感谢您的链接!很抱歉被骗了。我知道 findOne 但我听说它已被弃用,不确定有什么区别。无论哪种方式,链接都有帮助
-
很高兴它有帮助。
findOne绝对不会被弃用;你从哪里听到的? -
@JohnnyHK 我的 IDE IntelliJ Idea,但它肯定是错的。我编辑了我的问题以包含屏幕截图
标签: javascript node.js mongodb express