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
});
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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With