Reputation: 103
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..
Upvotes: 4
Views: 13731
Reputation: 1454
Probably I'm late answering to this question. I've started working with nodejs
and I'm using MongoDB for store all the data and I had the same problem finding a solution to keep the documents in a variable.
As you may know, the queries are async and in that way you can't assign the result in a variable, instead of doing that you have to use a function as a callback and return the value there.
Here's a sample code that I'm using in my project:
var verifyUserExists = function(db, callback, username) {
var collection = db.collection('users');
collection.findOne({ 'login': username }, function(err, doc) {
assert.equal(null, err);
callback(doc);
});
}
mongoClient.connect(mongoUrl, function(err, db) {
assert.equal(null, err);
console.log('Connected successfully to server');
verifyUserExists(db, function(userExists) {
console.log(userExists);
db.close();
}, username);
});
If you want to do other operations with the returned documents you have to do it in the callback, if you try to return the value in the callback function to a global variable you will get undefined
because the code is executed async.
Upvotes: 0
Reputation:
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.
Upvotes: 3