Search code examples
javascriptnode.jsmongoosepromisebluebird

Mongoose: ".find(...).exec(...).then(...).catch(...).finally is not a function" using bluebird?


I am currently trying to use Promises with Mongoose. I've read that as of 4.1, mPromise had been added as well as the the ability to plug external promises libraries such as bluebird or q.

I have no issues with basic promises that only a need then and catch however, when I try to use finally, a Bluebird method, I end up not being able to do so, with the aforementioned error. Here is a code snippet:

mongoose.connect(uri, { useMongoClient: true, promiseLibrary: require('bluebird')})
                .then(() => {
                    MyModel.find(query).exec()
                        .then(res => resolve(res) 
                        .catch(err => reject(err))
                        .finally(() => {
                            mongoose.connection.close();
                        });
                })
                .catch(err => console.error(err));

I also made sure to require bluebird

var Promise = require('bluebird');
var mongoose = require('mongoose');
mongoose.Promise = Promise;

Any idea on why mongoose isn't returning a Bluebird promise ?

Thanks


Solution

  • And of course, after a few hours of struggle, I post on SO and find the answer :) Thanks to this answer by Anton Novik https://stackoverflow.com/a/42313136/8569785 in another thread I've managed to plug bluebird.

    It turns out that one of the files in the project had a

    var mongoose = require('mongoose');
    mongoose.promise = require('bluebird');
    

    Follow by another assignment a few lines later that had gone unnoticed:

    mongoose.promise = global.Promise // Effectively assigning mongoose promise to the native implementation, oops ! 
    

    After deleting the assignment, and making sure that every mongoose assignment is a local scope one, this is now resolved !