kkaul
kkaul

Reputation: 38

Way to use mongodb's find cursor's next/each functions as a promise after promisifying mongodb with Bluebird

This is my code sample :

var findAsync = function (collection,query) {
    return mongodb.MongoClient.connectAsync(mongodbServerString)
    .then(function (db) {
        return [db.collection(collection).find(query), db];
    });
};

findAsync("UserProfile",{})
.spread(function (cursor,db) {
    return [cursor.project({Email:true}),db];
})
.spread(function (cursor, db) {
    return cursor.eachAsync().then(function (doc) {
        console.log(doc);
    }).catch(function () {
        db.close();
    });
});

Upvotes: 1

Views: 1106

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276406

Promises represent singular values. Promises are basically like function returns, since a function cannot return multiple values - it wouldn't make sense to convert each to a promise returning function.

What you can do is either convert it to an Observable returning function and then use .forEach on that to get a promise back for the completion of the sequence or you can implement something similar manually:

function each(cursor, fn) {
    return new Promise((resolve, reject) => {
        cursor.forEach((err, data) => {
           if(err) {
             cursor.close();
             return reject(err);
           }
           try { fn(data); } catch(e) { cursor.close(); reject(e); }
        }, err => { { // finished callback
           if(err) reject(err);
           else resolve();
        });
    });
}

Which would let you write:

each(cursor, doc => console.log(doc)).then(...).catch(...)

Also note that Mongo connections are persistent, you're supposed to connect once when the server starts and then keep the connection open for as long as the server is run.

Upvotes: 1

Related Questions