Skip to content

Commit

Permalink
Merge pull request jugglingdb#21 from sagish/master
Browse files Browse the repository at this point in the history
better mongodb query performance
  • Loading branch information
1602 committed Sep 4, 2013
2 parents 65eea43 + 7768523 commit c9cac78
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 21 deletions.
40 changes: 19 additions & 21 deletions lib/mongodb.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,8 @@ MongoDB.prototype.exists = function (model, id, callback) {
if (typeof id === 'string') {
id = new ObjectID(id);
}
this.collection(model).findOne({_id: id}, function (err, data) {
callback(err, !!(!err && data));
this.collection(model).findOne({_id: id}, {_id: 1}, function (err, data) {
callback(err, !!(data && data._id));
});
};

Expand All @@ -161,26 +161,24 @@ MongoDB.prototype.find = function find(model, id, callback) {
};

MongoDB.prototype.updateOrCreate = function updateOrCreate(model, data, callback) {
var adapter = this;
if (!data.id) return this.create(model, data, callback);
this.find(model, data.id, function (err, inst) {
if (err) return callback(err);
if (inst) {
adapter.updateAttributes(model, data.id, data, callback);
} else {
data._id = data.id;
delete data.id;
adapter.create(model, data, function (err, id) {
if (err) return callback(err);
if (id) {
data.id = id;
delete data._id;
callback(null, data);
} else{
callback(null, null); // wtf?
}
});

// set data.id as a mongodb object
if (data.id) {
if (typeof data.id === "string") {
data.id = new ObjectID(data.id);
}
}
else {
data.id = data._id ? data._id : new ObjectID()
}

// avoid setting data._id during $set method
if (data._id) {
delete data._id;
}

this.collection(model).update({_id: data.id}, {$set: data}, {upsert: true, multi: false}, function(err, rowsAffected) {
callback(err, data);
});
};

Expand Down
24 changes: 24 additions & 0 deletions test/mongodb.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,30 @@ describe('mongodb', function(){
});
});

it('should create and update an object using upsert', function(done) {
var id = new db.ObjectID;
var email = '[email protected]';
var updatedEmail = '[email protected]';
User.upsert({id: id, email: email}, function(err, user) {
should.not.exist(err);
should.exist(user);
user.email.should.equal(email);
user.id.toString().should.equal(id.toString());
User.find(id, function(err, user){
should.not.exist(err);
user.email.should.equal(email);
User.upsert({id: id, email: updatedEmail}, function(err, user){
User.find(id, function(err, user) {
should.not.exist(err);
user.id.should.equal(id);
user.email.should.equal(updatedEmail);
done();
});
});
})
});
});

after(function(done){
User.destroyAll(function(){
Post.destroyAll(function() {
Expand Down

0 comments on commit c9cac78

Please sign in to comment.