From bc835f59d4bf4d39f443497a39331b30e08a1fc5 Mon Sep 17 00:00:00 2001 From: Baris Soner Usakli Date: Mon, 13 Jan 2014 20:46:43 -0500 Subject: [PATCH] mongo getListRange fix --- src/database/mongo.js | 37 ++++++++++++++++++++++++++++++++----- src/routes/debug.js | 1 + 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/src/database/mongo.js b/src/database/mongo.js index 5f27c9da90..83e6eb8dec 100644 --- a/src/database/mongo.js +++ b/src/database/mongo.js @@ -741,17 +741,44 @@ module.getListRange = function(key, start, stop, callback) { - if(stop === -1) { - // mongo doesnt allow -1 as the count argument in slice - // pass in a large value to retrieve the whole array - stop = Math.pow(2, 31) - 2; + var skip = start, + limit = stop - start + 1, + splice = false; + + if((start < 0 && stop >= 0) || (start >= 0 && stop < 0)) { + skip = 0; + limit = Math.pow(2, 31) - 2; + splice = true; + } else if (start > stop) { + return callback(null, []); } - db.collection('objects').findOne({_key:key}, { array: { $slice: [start, stop - start + 1] }}, function(err, data) { + db.collection('objects').findOne({_key:key}, { array: { $slice: [skip, limit] }}, function(err, data) { if(err) { return callback(err); } + if(data && data.array) { + if(splice) { + + if(start < 0) { + start = data.array.length - Math.abs(start); + } + + if(stop < 0) { + stop = data.array.length - Math.abs(stop); + } + + if(start > stop) { + return callback(null, []); + } + + var howMany = stop - start + 1; + if(start !== 0 || howMany !== data.array.length) { + data.array = data.array.splice(start, howMany); + } + } + callback(null, data.array); } else { callback(null, []); diff --git a/src/routes/debug.js b/src/routes/debug.js index 147df9d13c..c31684a6dd 100644 --- a/src/routes/debug.js +++ b/src/routes/debug.js @@ -82,6 +82,7 @@ var DebugRoute = function(app) { app.get('/test', function(req, res) { res.send(); }); + }); };