I am working on a node.js project in which I need to communicate with a mongoDb database. I am currently programming a function to find some data in my db using th node-mongodb-native module. Everything works, but my code looks like a callback in a callback in a callback in a callback...
I created this function to prevent me from using callbacks every time I want to access my database. I now just need to call this function.
module.exports.find = function(query, projection, callback){
db.open(function(err, db){
if(err) throw err;
db.collection('rooms', function(err, collection){
if(err) throw err;
collection.find(query, projection, function(err, cursor){
if (err) throw err;
cursor.toArray(function(err, find){
db.close();
callback(err, find);
});
});
});
});
};
Is there a method to reduce this codeception ?
Thank you :)
I am sorry if my English is not really good, I am learning it.
If you just want to know how to cleanup callbacks reasonably and scope db:
module.exports.find = function(query, projection, callback){
var local_db;
function db_open(err, db) {
if(err) throw err;
local_db = db;
local_db.collection('rooms', handle_homes_collection);
}
function handle_homes_collection(err, collection){
if(err) throw err;
collection.find(query, projection, handle_find_query);
}
function handle_find_query(err, cursor){
if (err) throw err;
cursor.toArray(function(err, find){
local_db.close();
callback(err, find);
});
}
db.open(db_open);
};
Like this:
module.exports.find = function(query, projection, callback){
var database;
db.open(function(err, db_temp){
if(err) throw err;
database = db_temp;
});
database.collection('rooms', function(err, collection){
if(err) throw err;
collection.find(query, projection, function(err, cursor){
if (err) throw err;
cursor.toArray(function(err, find){
db.close();
callback(err, find);
});
});
});
};