For some reason, I can't get the following to work return a document queried from my mongodb database using the node.js driver.
function findSomething(){
const database = "learning";
const collection = "stuff";
var str;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db(database);
dbo.collection(collection).findOne({}, function(err, result) {
if (err) throw err;
str = result.name;
db.close();
});
});
return str;
}
console.log(findSomething());
This outputs
undefined
However, if I modify my above code to include the following
console.log(str);
right after
str = result.name;
It will result in the following output:
undefined
Company Inc //sample data from my document
The two things I don't understand are;
- Why I can't assign str outside the .connect() function, and why the value it is assigned is lost once the connection is closed
- Why the .connect() function executes after a value is returned by the findSomething() function.
I understand that my second concern will answer my first, and I am trying to do this so I can modularize my mongodb crud functions so as to make everything cleaner in my express app.