I am pretty new to Node.js and I am using the MongoDb driver, I understand the workflow of Node.js is eventdriven and everything runs asynchronous but I just don’t understand how I can do things like this:
var mongo = require('mongodb');
var db = new mongo.Db('meta', new mongo.Server('localhost', 27017, { auto_reconnect: true }));
db.open(function(error, db){
if(error){
throw error;
}
db.collection('logs', function(error, collection){
if(!collection){
db.createCollection('logs', callback); // How does this callback works? I mean, how can we continue the previous execution of the script?
}
// Have fun.
});
});
So with the script above I want to:
- Open the connection
- Check for logs collection, if not create, else continue…
- Create a user? Do work?
I am still getting used to the Asynchronous model, thanks for help already.
What I usually do in this sort of scenario is wrap the continuation in a named callback:
That being said, the
createCollectionmethod will also return the collection object and only create it if it does not already exist. You can just write: