Use cursor to find documents

pull/2/head
Louis Chatriot 11 years ago
parent 7632ac14b3
commit a981aa3675
  1. 54
      lib/cursor.js
  2. 47
      lib/datastore.js

@ -0,0 +1,54 @@
/**
* Manage access to data, be it to find, update or remove it
*/
var model = require('./model');
/**
* Create a new cursor for this collection
* @param {Datastore} db - The datastore this cursor is bound to
* @param {Query} query - The query this cursor will operate on
*/
function Cursor (db, query) {
this.db = db;
this.query = query;
}
/**
* Set a limit the number of results
*/
Cursor.prototype.limit = function(limit) {
this.limit = limit;
};
/**
* Get all matching elements
* @param {Function} callback - Signature: err, results
*/
Cursor.prototype.exec = function(callback) {
var candidates = this.db.getCandidates(this.query)
, res = [], added = 0
, i
;
try {
for (i = 0; i < candidates.length; i += 1) {
if (model.match(candidates[i], this.query)) {
res.push(model.deepCopy(candidates[i]));
added += 1;
if (this.limit && this.limit <= added) { break; }
}
}
} catch (err) {
return callback(err);
}
return callback(null, res);
};
// Interface
module.exports = Cursor;

@ -6,6 +6,7 @@ var customUtils = require('./customUtils')
, util = require('util')
, _ = require('underscore')
, Persistence = require('./persistence')
, Cursor = require('./cursor')
;
@ -374,11 +375,11 @@ Datastore.prototype._count = function(query, callback) {
}
return callback(null, res);
}
};
Datastore.prototype.count = function() {
this.executor.push({this: this, fn: this._count, arguments: arguments });
}
};
/**
* Find all documents matching the query
@ -387,23 +388,8 @@ Datastore.prototype.count = function() {
* @api private Use find
*/
Datastore.prototype._find = function (query, callback) {
var res = []
, self = this
, candidates = this.getCandidates(query)
, i
;
try {
for (i = 0; i < candidates.length; i += 1) {
if (model.match(candidates[i], query)) {
res.push(model.deepCopy(candidates[i]));
}
}
} catch (err) {
return callback(err);
}
return callback(null, res);
var cursor = new Cursor(this, query);
cursor.exec(callback);
};
Datastore.prototype.find = function () {
@ -418,22 +404,15 @@ Datastore.prototype.find = function () {
* @api private Use findOne
*/
Datastore.prototype._findOne = function (query, callback) {
var self = this
, candidates = this.getCandidates(query)
, i, found = null
;
try {
for (i = 0; i < candidates.length; i += 1) {
if (model.match(candidates[i], query)) {
found = model.deepCopy(candidates[i]);
}
var cursor = new Cursor(this, query);
cursor.limit(1);
cursor.exec(function (err, docs) {
if (err) {
return callback(err);
} else {
return callback(null, docs.length === 1 ? docs[0] : null);
}
} catch (err) {
return callback(err);
}
return callback(null, found);
});
};
Datastore.prototype.findOne = function () {

Loading…
Cancel
Save