Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I store a mongodb query result in a variable?

I am having the hardest time finding a solution to something that should be so simple.. I would like to find a document in a mongo database and store it in a variable that i can use anywhere in a node.js app..

The closest I think I have gotten is

var path = db.collection('paths').find().toArray()

where path is a collection holding one document, but then console.log(path[0]) returns undefined..

like image 994
jjames Avatar asked Sep 12 '25 09:09

jjames


1 Answers

Try asynchronous way, something like this

var path;
db.collection('paths', function(err, collection) {
    collection.find({}).toArray(function(err, results) {
        path = results;
        console.log(results);
    });
});

NOTE
Never try to run IO operation synchronously in node.js because node.js is single threaded. If you do, you would block the whole application. The api provided by mongodb nodejs native is asynchronous, that means the result is expected in some point of time in future but not immediately. As soon as the result is available callback function is called and you get your result.

If you are coming from synchronous coding background, its a paradigm shift. You need to change your mind to think asynchronously.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!