I am new to node/Mongo, and I have already run what I gather is "callback hell". Here's a simple example I copied from the book. It simply connects to mongo, adds and drops a collection and logs these operations:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://dbadmin:da@localhost:27017/", function(err, db) {
var newDB = db.db("newDB");
newDB.collectionNames(function(err, collectionNames) {
console.log("Initial collections: ");
console.log(collectionNames);
newDB.createCollection("newCollection", function (err, collection){
newDB.collectionNames( function (err, collectionNames) {
console.log("Collections after creation: ");
console.log(collectionNames);
newDB.dropCollection("newCollection", function (err, results) {
newDB.collectionNames( function (err, collectionNames) {
console.log("Collections after deletion: ");
console.log(collectionNames);
db.close();
});
});
});
});
});
});
This code works, but it already seems really hard to read and maintain. I have been researching what to do about this, and there seems to be differing opinions out there. If someone could offer an alternative way to code this, which library dependency, if any, does the best job, and a re-write of this example, it would be greatly appreciated!!!