Daniel Billingham Daniel Billingham - 5 months ago 10
Node.js Question

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
});

Answer

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.