-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
50 lines (47 loc) · 1.31 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
/*!
* Mongoose findOrCreate Plugin
* Copyright(c) 2012 Nicholas Penree <nick@penree.com>
* MIT Licensed
*/
function findOrCreatePlugin(schema, options) {
schema.statics.findOrCreate = function findOrCreate(conditions, doc, options, callback) {
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 = {};
}
}
var self = this;
this.findOne(conditions, function(err, result) {
if(err || result) {
if(options && options.upsert && !err) {
self.update(conditions, doc, function(err, count){
self.findOne(conditions, function(err, result) {
callback(err, result, false);
});
})
} else {
callback(err, result, false)
}
} else {
for (var key in doc) {
conditions[key] = doc[key];
}
var obj = new self(conditions)
obj.save(function(err) {
callback(err, obj, true);
});
}
})
}
}
/**
* Expose `findOrCreatePlugin`.
*/
module.exports = findOrCreatePlugin;