Skip to content

Commit

Permalink
Merge pull request #36 from AanshSavla/promise_callback_issue
Browse files Browse the repository at this point in the history
Promise and findOne Callback code changed
  • Loading branch information
drudge authored Mar 27, 2023
2 parents dd683bd + 1ee2b43 commit b0f3593
Show file tree
Hide file tree
Showing 4 changed files with 2,010 additions and 297 deletions.
61 changes: 41 additions & 20 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
function findOrCreatePlugin(schema, options) {
schema.statics.findOrCreate = function findOrCreate(conditions, doc, options, callback) {
var self = this;
// When using Mongoose 5.0.x and upper, we must use self.base.Promise
var Promise = self.base.Promise.ES6 ? self.base.Promise.ES6 : self.base.Promise;

var Promise = global.Promise.ES6 ? global.Promise.ES6 : global.Promise;
if (arguments.length < 4) {
if (typeof options === 'function') {
// Scenario: findOrCreate(conditions, doc, callback)
Expand All @@ -35,31 +35,52 @@ function findOrCreatePlugin(schema, options) {
});
}
}
this.findOne(conditions, function(err, result) {
if (err || result) {
if (options && options.upsert && !err) {
self.update(conditions, doc, function(err, count) {
self.findById(result._id, function(err, result) {
callback(err, result, false);
});
});
} else {
callback(err, result, false);
}
} else {
for (var key in doc) {
conditions[key] = doc[key];
//mongoose 7.0.x does not support callbacks so we use findOne().exec().then().catch()
this.findOne(conditions).exec().then(function(result){
if(result == null){
for(var key in doc){
conditions[key] = doc[key];
}

// Prune any keys starting with `$` since those are query operators and not data.
// This library does not support models which have keys starting with `$`.
removeQueryOperators(conditions);

var obj = new self(conditions);
obj.save(function(err) {
callback(err, obj, true);
obj.save().then(function(result){
err = null;
callback(err,obj,true);
}).catch(function(err){
result = null;
callback(err,result,false);
});

}
else{
if(options && options.upsert){
self.updateOne(conditions,doc).exec().then(function(count){
self.findById(result._id).exec().then(function(result){

err = null;
callback(err,result,false);
}).catch(function(err){
result = null;
callback(err,result,false);
});
}).catch(function(err){
result = null;
callback(err,result,false);
});
}
else{

err = null;
callback(err,result,false);
}
}


}).catch(function(err){
result = null;
callback(err,result,false);
});
};
}
Expand Down
Loading

0 comments on commit b0f3593

Please sign in to comment.