Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

added upsert option

  • Loading branch information...
commit 57dc7e99e866dfad354697234a67a9b789210e0f 1 parent cb92aa4
@romanmt romanmt authored
Showing with 40 additions and 10 deletions.
  1. +23 −7 index.js
  2. +2 −2 package.json
  3. +15 −1 test/index_test.js
View
30 index.js
@@ -5,17 +5,33 @@ _.mixin(_.str.exports());
module.exports = exports = function superGoosePlugin(schema, options) {
if(options) var messages = options.messages
- schema.statics.findOrCreate = function findOrCreate(object, properties, callback) {
- if(_.isFunction(properties)) {
- callback = properties
- properties = {}
+ schema.statics.findOrCreate = function findOrCreate(conditions, doc, options, callback) {
+ if (arguments.length < 4) {
+ if (_.isFunction(options)) {
+ // Scenario: findOrCreate(conditions, doc, callback)
+ callback = options;
+ options = {};
+ } else if (_.isFunction(doc)) {
+ // Scenario: findOrCreate(doc, callback);
+ callback = doc;
+ doc = conditions;
+ conditions = {};
+ options = {};
+ }
}
var self = this;
- this.findOne(object, function(err, result) {
+ this.findOne(conditions, function(err, result) {
if(err || result) {
- callback(err, result)
+ if(options && options.upsert && !err) {
+ self.update(result, doc, function(err, count){
+ self.findOne(conditions, callback);
+ })
+ } else {
+ callback(err, result)
+ }
} else {
- var obj = new self(_.extend(object, properties))
+ _.extend(conditions, doc)
+ var obj = new self(conditions)
obj.save(function(err) {
callback(err, obj)
});
View
4 package.json
@@ -1,8 +1,8 @@
{
"name": "supergoose"
, "description": "Mongoose plugin for simple addons like findOrCreate"
- , "version": "0.0.5"
- , "author": "Matt Roman"
+ , "version": "0.0.6"
+ , "author": "Matt Roman <romanmt@gmail.com>"
, "keywords": ["supergoose", "mongodb", "mongoose", "plugin", "findOrCreate"]
, "repository": {
"type": "git"
View
16 test/index_test.js
@@ -22,7 +22,7 @@ var messages = {
ClickSchema.plugin(supergoose, {messages: messages});
var Click = mongoose.model('Click', ClickSchema);
-beforeEach(function(done) {
+afterEach(function(done) {
Click.collection.remove()
done();
})
@@ -68,6 +68,20 @@ describe('findOrCreate', function() {
})
})
})
+
+ describe('with upsert', function() {
+ it("updates the existing object", function(done) {
+ Click.create({ip: '127.0.0.1', browser: 'Chrome'}, function(err, val) {
+ Click.findOrCreate({ip: '127.0.0.1'}, {browser: 'IE'}, {upsert: true}, function(err, click) {
+ click.should.have.property('browser', 'IE')
+ Click.count({}, function(err, num) {
+ num.should.equal(1)
+ done();
+ })
+ })
+ })
+ })
+ })
})
describe('errorMessages', function() {
Please sign in to comment.
Something went wrong with that request. Please try again.