77function findOrCreatePlugin ( schema , options ) {
88 schema . statics . findOrCreate = function findOrCreate ( conditions , doc , options , callback ) {
99 var self = this ;
10- // When using Mongoose 5.0.x and upper, we must use self.base.Promise
11- var Promise = self . base . Promise . ES6 ? self . base . Promise . ES6 : self . base . Promise ;
10+
11+ var Promise = global . Promise . ES6 ? global . Promise . ES6 : global . Promise ;
1212 if ( arguments . length < 4 ) {
1313 if ( typeof options === 'function' ) {
1414 // Scenario: findOrCreate(conditions, doc, callback)
@@ -35,31 +35,52 @@ function findOrCreatePlugin(schema, options) {
3535 } ) ;
3636 }
3737 }
38- this . findOne ( conditions , function ( err , result ) {
39- if ( err || result ) {
40- if ( options && options . upsert && ! err ) {
41- self . update ( conditions , doc , function ( err , count ) {
42- self . findById ( result . _id , function ( err , result ) {
43- callback ( err , result , false ) ;
44- } ) ;
45- } ) ;
46- } else {
47- callback ( err , result , false ) ;
48- }
49- } else {
50- for ( var key in doc ) {
51- conditions [ key ] = doc [ key ] ;
38+ //mongoose 7.0.x does not support callbacks so we use findOne().exec().then().catch()
39+ this . findOne ( conditions ) . exec ( ) . then ( function ( result ) {
40+ if ( result == null ) {
41+ for ( var key in doc ) {
42+ conditions [ key ] = doc [ key ] ;
5243 }
53-
5444 // Prune any keys starting with `$` since those are query operators and not data.
5545 // This library does not support models which have keys starting with `$`.
5646 removeQueryOperators ( conditions ) ;
57-
5847 var obj = new self ( conditions ) ;
59- obj . save ( function ( err ) {
60- callback ( err , obj , true ) ;
48+ obj . save ( ) . then ( function ( result ) {
49+ err = null ;
50+ callback ( err , obj , true ) ;
51+ } ) . catch ( function ( err ) {
52+ result = null ;
53+ callback ( err , result , false ) ;
6154 } ) ;
55+
6256 }
57+ else {
58+ if ( options && options . upsert ) {
59+ self . updateOne ( conditions , doc ) . exec ( ) . then ( function ( count ) {
60+ self . findById ( result . _id ) . exec ( ) . then ( function ( result ) {
61+
62+ err = null ;
63+ callback ( err , result , false ) ;
64+ } ) . catch ( function ( err ) {
65+ result = null ;
66+ callback ( err , result , false ) ;
67+ } ) ;
68+ } ) . catch ( function ( err ) {
69+ result = null ;
70+ callback ( err , result , false ) ;
71+ } ) ;
72+ }
73+ else {
74+
75+ err = null ;
76+ callback ( err , result , false ) ;
77+ }
78+ }
79+
80+
81+ } ) . catch ( function ( err ) {
82+ result = null ;
83+ callback ( err , result , false ) ;
6384 } ) ;
6485 } ;
6586}
0 commit comments