diff --git a/lib/datastore.js b/lib/datastore.js index 40943fd..cade891 100644 --- a/lib/datastore.js +++ b/lib/datastore.js @@ -404,7 +404,6 @@ Datastore.prototype.find = function (query, projection, callback) { }); cursor.projection(projection); - if (typeof callback === 'function') { cursor.exec(callback); } else { @@ -416,8 +415,22 @@ Datastore.prototype.find = function (query, projection, callback) { /** * Find one document matching the query * @param {Object} query MongoDB-style query + * @param {Object} projection MongoDB-style projection */ -Datastore.prototype.findOne = function (query, callback) { +Datastore.prototype.findOne = function (query, projection, callback) { + switch (arguments.length) { + case 1: + projection = {}; + // callback is undefined, will return a cursor + break; + case 2: + if (typeof projection === 'function') { + callback = projection; + projection = {}; + } // If not assume projection is an object and callback undefined + break; + } + var cursor = new Cursor(this, query, function(err, docs, callback) { if (err) { return callback(err); } if (docs.length === 1) { @@ -427,7 +440,7 @@ Datastore.prototype.findOne = function (query, callback) { } }); - cursor.limit(1); + cursor.projection(projection).limit(1); if (typeof callback === 'function') { cursor.exec(callback); } else { diff --git a/test/db.test.js b/test/db.test.js index d656d34..a02bf3d 100644 --- a/test/db.test.js +++ b/test/db.test.js @@ -661,7 +661,7 @@ describe('Database', function () { }); }); - it.only('Can use projections in find, normal or cursor way', function (done) { + it('Can use projections in find, normal or cursor way', function (done) { d.insert({ a: 2, hello: 'world' }, function (err, doc0) { d.insert({ a: 24, hello: 'earth' }, function (err, doc1) { d.find({ a: 2 }, { a: 0, _id: 0 }, function (err, docs) { @@ -692,6 +692,35 @@ describe('Database', function () { }); }); + it('Can use projections in findOne, normal or cursor way', function (done) { + d.insert({ a: 2, hello: 'world' }, function (err, doc0) { + d.insert({ a: 24, hello: 'earth' }, function (err, doc1) { + d.findOne({ a: 2 }, { a: 0, _id: 0 }, function (err, doc) { + assert.isNull(err); + assert.deepEqual(doc, { hello: 'world' }); + + d.findOne({ a: 2 }, { a: 0, _id: 0 }).exec(function (err, doc) { + assert.isNull(err); + assert.deepEqual(doc, { hello: 'world' }); + + // Can't use both modes at once if not _id + d.findOne({ a: 2 }, { a: 0, hello: 1 }, function (err, doc) { + assert.isNotNull(err); + assert.isUndefined(doc); + + d.findOne({ a: 2 }, { a: 0, hello: 1 }).exec(function (err, doc) { + assert.isNotNull(err); + assert.isUndefined(doc); + + done(); + }); + }); + }); + }); + }); + }); + }); + }); // ==== End of 'Find' ==== // describe('Count', function() {