Why can't I connect .catch when calling mongoose Model.create in node

I have a mongoose circuit and I call Model.create ().

When the catch chain after "then" I get undefined is not a function, if I just call the error function as the second parameter in "then", then I do not.

But when I call methods like Model.find, I can use "catch".

Why I can not intercept "catch" when calling Model.create

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

Working:

 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 }); 
+7
promise mongodb mongoose
source share
3 answers

After that, it looks like this: .catch is not actually part of the Promises / A + specification. Most libraries seem to implement it as syntactic sugar. The MPromise library is a promise library for Mongoose, and it looks like it meets the minimum specification requirements. You can try using a different promise library to wrap Mongoose promises, but it would be easier to just pull it in and stick to the standard .then(success, error) handler.

If you want to wrap them, you can do it 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 almost every popular promise library has this ability.

+8
source share

As indicated at http://mongoosejs.com/docs/promises.html

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

You can install mongoose to use bluebird using:

 require("mongoose").Promise = require("bluebird"); 
+11
source share

At some point, mpromise seems to have added .catch() support. I use mongoose@4.5.1 and .catch() working correctly as expected.

+6
source share

All Articles