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:
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:
if (!collection) {
db.createCollection('logs', next);
} else {
next(null, collection);
}
function next(err, collection) {
// do something
}
That being said, the createCollection
method will also return the collection object and only create it if it does not already exist. You can just write:
db.createCollection('logs', function(err, collection) {
// do something
});