Skip to content

Commit

Permalink
Added support for upserts on create/insert
Browse files Browse the repository at this point in the history
  • Loading branch information
notheotherben committed May 28, 2014
1 parent 52013e4 commit fbe4246
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 6 deletions.
23 changes: 17 additions & 6 deletions lib/Model.js
Original file line number Diff line number Diff line change
Expand Up @@ -506,14 +506,25 @@ Model.prototype.insert = Model.prototype.create = function (object, options, cal
return callback(err, results[0]);
}).bind(this);

var queryOptions = { w: callback ? 1 : 0, upsert: !!options.upsert, new: true };

var prepComplete = (function(err, prepped) {
if(err) return end(err);
this.collection.insert(prepped, { w: callback ? 1 : 0 }, (function(err, inserted) {
if (err) return end(err);
if(callback)
return this.onRetrieved(null, inserted, end, null, { wrap: options.wrap, cache: options.cache });
return end();
}).bind(this));

if(queryOptions.upsert)
this.collection.findAndModify({ _id: prepped._id }, { _id: 1 }, prepped, queryOptions, (function(err, inserted) {
if (err) return end(err);
if(callback)
return this.onRetrieved(null, inserted[0], end, null, { wrap: options.wrap, cache: options.cache });
return end();
}).bind(this));
else
this.collection.insert(prepped, queryOptions, (function(err, inserted) {
if (err) return end(err);
if(callback)
return this.onRetrieved(null, inserted, end, null, { wrap: options.wrap, cache: options.cache });
return end();
}).bind(this));
}).bind(this);

async.parallel(_.map(object, function(obj) {
Expand Down
24 changes: 24 additions & 0 deletions test/insertion.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,30 @@ describe('orm', function () {
done();
});
});

it('should support upsert operations on new documents', function(done) {
model.create({
name: 'Demo4',
upserted: true
}, { upsert: true }, function(err, updated) {
should.not.exist(err);
should.exist(updated);
updated.should.have.property('upserted').and.equal(true);
done();
});
});

it('should support upsert operations on existing documents', function(done) {
model.create({
name: 'Demo1',
upserted: true
}, { upsert: true }, function(err, updated) {
should.not.exist(err);
should.exist(updated);
updated.should.have.property('upserted').and.equal(true);
done();
});
});
});
});
});
Expand Down

0 comments on commit fbe4246

Please sign in to comment.