As a newcomer to Node Express Mongo, I decided to venture into creating my own website after following tutorials. The page I'm working on is a login
page. While other people's code has worked for me, my attempt didn't go as planned. Even consulting the documentation and trying to mimic their examples like db.bios.find( { _id: 5 } )
hasn't helped.
The database I am using is named ShipDB
, with a collection called users
. The specific document I'm searching for is:
{
"_id" : ObjectId("56edc18064e429581541808a"),
"username" : "username",
"password" : "password"
}
After connecting to the database, when checking result.length
for redirection, it always appears as undefined even though I input the correct username
and password
. Here's what I see in 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);
}
});
});
Attempts made so far include:
user_collection.find(user_login_input, function(err, result) {...
user_collection.find({ "username": req.body.username, "password": req.body.password })...
This works on mongoshell:
https://i.stack.imgur.com/V3KNG.png
Your time and insights are greatly appreciated.
Edit: It seems like findOne
might be deprecated based on this feedback: