-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
108 lines (97 loc) · 2.95 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*!
* Mongoose findOrCreate Plugin
* Copyright(c) 2012 Nicholas Penree <[email protected]>
* MIT Licensed
*/
function findOrCreatePlugin(schema, options) {
schema.statics.findOrCreate = function findOrCreate(conditions, doc, options, callback) {
var self = this;
var Promise = global.Promise.ES6 ? global.Promise.ES6 : global.Promise;
if (arguments.length < 4) {
if (typeof options === 'function') {
// Scenario: findOrCreate(conditions, doc, callback)
callback = options;
options = {};
} else if (typeof doc === 'function') {
// Scenario: findOrCreate(conditions, callback);
callback = doc;
doc = {};
options = {};
} else {
// Scenario: findOrCreate(conditions[, doc[, options]])
return new Promise(function(resolve, reject) {
self.findOrCreate(conditions, doc, options, function (ex, result, created) {
if (ex) {
reject(ex);
} else {
resolve({
doc: result,
created: created,
});
}
});
});
}
}
//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().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);
});
};
}
function removeQueryOperators(o) {
var keys = Object.keys(o);
for (var z = 0; z < keys.length; z++) {
var key = keys[z];
if (key[0] === '$') {
delete o[key];
} else {
var subObject = o[key];
if (typeof subObject === 'object' && subObject !== null) {
removeQueryOperators(subObject);
}
}
}
}
/**
* Expose `findOrCreatePlugin`.
*/
module.exports = findOrCreatePlugin;