Search code examples
javascriptnode.jsmongodbmongoosepromise

NodeJs Mongoose Promise then/catch


Faced an issue with Mongoose promises

MyModel.find().then((data)=> Promise.reject())
       .catch(()=>console.log('first catch'))
       .then(()=>console.log('ok'))
       .catch(()=>console.log('second catch'));

after the execution I get

first catch
second catch

But if I do it with only native Promises:

Promise.reject()
       .catch(()=>console.log('first catch'))
       .then(()=>console.log('ok'))
       .catch(()=>console.log('second catch'));

after the execution I get

first catch
ok

that is ok in terms of Promise docs

It seems that Mongoose uses own promise implementation

I have found that I can solve that by doing the following

new Promise((resolve, reject) => { MyModel.find().then((data) => reject()) })
       .catch(()=>console.log('first catch'))
       .then(()=>console.log('ok')
       .catch(()=>console.log('second catch'));

It works as it should according the docs:

first catch
ok

Any suggestion how to work with that better?


Solution

  • Mongoose uses Promises/A+ conformant promises. For backwards compatibility, Mongoose 4 returns mpromise promises by default.

    If you want to use advanced promise features, you should use library like bluebird or native ES6 promises. To do that just set mongoose.Promise to your favorite ES6-style promise constructor and mongoose will use it:

    require('mongoose').Promise = Promise;
    // or
    require('mongoose').Promise = require('bluebird');
    

    Mongoose documentation