Skip to content

Commit

Permalink
Fixed upsert behaviour with multiple documents
Browse files Browse the repository at this point in the history
  • Loading branch information
notheotherben committed May 28, 2014
1 parent 39e8373 commit 7e77e89
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
11 changes: 9 additions & 2 deletions lib/Model.js
Original file line number Diff line number Diff line change
Expand Up @@ -512,10 +512,17 @@ Model.prototype.insert = Model.prototype.create = function (object, options, cal
if(err) return end(err);

if(queryOptions.upsert)
this.collection.findAndModify({ _id: prepped._id }, { _id: 1 }, prepped, queryOptions, (function(err, inserted) {
async.parallel(_.map(prepped, function(doc) {
return (function(done) {
this.collection.findAndModify({ _id: doc._id }, { _id: 1 }, doc, queryOptions, function(err, result) {
if(err) return done(err);
return done(null, result);
});
}).bind(this);
}, this), (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 this.onRetrieved(null, inserted, end, null, { wrap: options.wrap, cache: options.cache });
return end();
}).bind(this));
else
Expand Down
15 changes: 15 additions & 0 deletions test/insertion.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,21 @@ describe('orm', function () {
done();
});
});

it('should support upsert operations with multiple documents', function(done) {
model.create([{
name: 'Demo1',
upserted: true
},{
name: 'Demo5',
upserted: true
}], { upsert: true }, function(err, updated) {
should.not.exist(err);
should.exist(updated);
updated.length.should.equal(2);
done();
});
});
});
});
});
Expand Down

0 comments on commit 7e77e89

Please sign in to comment.