Skip to content

Commit

Permalink
Add findOne method to Collection
Browse files Browse the repository at this point in the history
  • Loading branch information
erikolson186 committed May 12, 2017
1 parent 452057b commit a8bc729
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion src/collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class Collection {
}

/**
* Open a cursor and optionally filter documents and apply a projection.
* Open a cursor that satisfies the specified query criteria.
* @param {object} [expr] The query document to filter by.
* @param {object} [projection_spec] Specification for projection.
* @return {Cursor}
Expand All @@ -44,6 +44,35 @@ class Collection {
return cur;
}

/**
* Retrieve one document that satisfies the specified query criteria.
* @param {object} [expr] The query document to filter by.
* @param {object} [projection_spec] Specification for projection.
* @param {function} [cb] The result callback.
* @return {Promise}
*
* @example
* col.findOne({ x: 4, g: { $lt: 10 } }, { k: 0 });
*/
findOne(expr, projection_spec, cb) {
if (typeof projection_spec === 'function') {
cb = projection_spec;
projection_spec = null;
}

const deferred = Q.defer();
const cur = this.find(expr, projection_spec).limit(1);

cur.toArray((error, docs) => {
if (error) { deferred.reject(error); }
else { deferred.resolve(docs[0]); }
});

deferred.promise.nodeify(cb);

return deferred.promise;
}

/**
* Evaluate an aggregation framework pipeline.
* @param {object[]} pipeline The pipeline.
Expand Down

0 comments on commit a8bc729

Please sign in to comment.