forked from gigwell/supergoose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
56 lines (51 loc) · 1.5 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
/*!
* 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) {
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];
}
delete conditions.id;
delete conditions._id;
var obj = new self(conditions);
console.log('FIND OR CREATE DOC BEFORE SAVE', obj);
obj.save(function(err, o) {
console.log('FIND OR CREATE DOC AFTER SAVE', o);
callback(err, o, true);
});
}
})
}
}
/**
* Expose `findOrCreatePlugin`.
*/
module.exports = findOrCreatePlugin;