Search code examples
node.jsmongodbpromisebluebird

nodejs mongodb bluebird error: db.getCollectionAsync is not a function


I am trying to use bluebird for the first time to minimize callbacks and synchronisation issues. I am just using the native mongodb client with blue bird as follows:

var mongodb = require('mongodb');
var Promise = require("bluebird");
Promise.promisifyAll(mongodb);
var MongoClient = mongodb.MongoClient;

Then later on, in a module.exports object, I have:

  foofunc: function( callback ) {
    MongoClient.connectAsync(url)
    .then(function(db) {
      //MongoDB should create collection if its not already there
      console.log('... connect worked. OK now get bar collection');
      return db.getCollectionAsync('bar');
    })
    .then(function(col){
      //do something with the returned collection col
    })
    .catch(function(err){
        //handle errors
        console.log(err);
        return callback(err);
    });
  }

I call this from my server running on localhost. The connection works, but then right after, I get the error: Unhandled rejection TypeError: db.getCollectionAsync is not a function

What am I doing wrong? Is it because I am doing it all on the serverside? If so, how come the connect which is also suffixed with Async works? :-(


Solution

  • As far as i see you using native mongodb NodeJs driver.

    http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html

    If this is the case. Then you need to use

    return db.collection('bar');

    Also point to node here that this method is synchronous.

    This answer also might be helpful to you.

    How can I promisify the MongoDB native Javascript driver using bluebird?

    Hope this helps.