Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I not chain .catch when calling mongoose Model.create in node

I have a mongoose schema and am calling Model.create().

When I chain 'catch' after the 'then' I get undefined is not a function, if I just call the error function as the second parameter to the 'then', then I don't.

But when I call methods such as Model.find, I can use 'catch'.

Why can I not chain 'catch' when calling Model.create

var mySchema = Mongoose.Schema({
     name: String,
});

Works:

KarmaModel.create({
            "name": "ss,
        })
        .then(function() {
            //do somthing
        },function()=>{
            //do somthing
        });

Does not work:

KarmaModel.create({
            "name": "ss,
        })
        .then(function() {
            //do somthing
        }).catch(function()=>{
            //do somthing
        });
like image 572
Daniel Billingham Avatar asked Jun 05 '15 17:06

Daniel Billingham


2 Answers

As specified on http://mongoosejs.com/docs/promises.html

New in Mongoose 4.1.0 While mpromise is sufficient for basic use cases, advanced users may want to plug in their favorite ES6-style promises library like bluebird, or just use native ES6 promises. Just set mongoose.Promise to your favorite ES6-style promise constructor and mongoose will use it.

You can set mongoose to use bluebird using:

require("mongoose").Promise = require("bluebird");
like image 78
jbdemonte Avatar answered Nov 15 '22 22:11

jbdemonte


After going over it, it looks like .catch isn't actually part of the Promises/A+ specification. Most libraries just seem to implement it as syntactic sugar. The MPromise library is the promise library for Mongoose and it looks like it adheres to the bare minimum requirements of the specification. You could try using another promise library to wrap Mongoose promises, but it might be easier to just suck it up and stick with the standard .then(success, error) handler.

If you do want to wrap them, you can do so like this:

var Promise = require('bluebird');
Promise.resolve(KarmaModel.create({ "name": "ss" })
  .then(function() {
    // do something
  })
  .catch(function() {
    // do something
  });

Bluebird is my favorite implementation, but nearly any popular promise library has this ability.

like image 43
Chev Avatar answered Nov 15 '22 22:11

Chev