Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: Using Promises with MongoDb

I've started using the Q Promise package in a simple node.js application. So I'm interested in how I can close the db connection after all promise sequence is complete.

Example:

var toDbConnectionString = function(dbSettings) {
    return "mongodb://" +
        dbSettings.user + ":" +
        dbSettings.password + "@" +
        dbSettings.url;
};

var connectionString = toDbConnectionString(dbSettings);

Q.nfcall(
    MongoClient.connect,
    toDbConnectionString(dbSettings))
.then(function(db) {
    return Q.ninvoke(db, "collectionNames");
})
.then(function(collections) {
    console.log(collections);
})
.catch(function() {
    console.log(arguments);
});

I want to close the connection after displaying the collection names but there's no db context in this anonymous function.

Is there the way how to handle such cases with the promise pattern?

like image 748
shadeglare Avatar asked Mar 22 '23 05:03

shadeglare


1 Answers

If you don't want to do nesting (I certainly don't...) then you can just do like so:

var toDbConnectionString = function(dbSettings) {
    return "mongodb://" +
        dbSettings.user + ":" +
        dbSettings.password + "@" +
        dbSettings.url;
};

var connectionString = toDbConnectionString(dbSettings);
var db;

Q.nfcall(
    MongoClient.connect,
    toDbConnectionString(dbSettings))
.then(function(_db) {
    db = _db;
    return Q.ninvoke(db, "collectionNames");
})
.then(function(collections) {
    console.log(collections);
})
.catch(function() {
    console.log(arguments);
})
.finally(function() {
    if (db) db.close();
});
like image 123
Esailija Avatar answered Apr 02 '23 18:04

Esailija