From 72387fdabc2d5f012c52ae8407e42cc0c8b72b70 Mon Sep 17 00:00:00 2001 From: Louis Chatriot Date: Fri, 25 Sep 2015 23:24:36 +0200 Subject: [PATCH] Fixed problem --- lib/indexes.js | 16 +++++++++++++--- test/db.test.js | 9 +++++++++ test/indexes.test.js | 14 +++++++++----- 3 files changed, 31 insertions(+), 8 deletions(-) diff --git a/lib/indexes.js b/lib/indexes.js index 13e1a3c..79227ce 100644 --- a/lib/indexes.js +++ b/lib/indexes.js @@ -246,13 +246,23 @@ function append (array, toAppend) { * @return {Array of documents} */ Index.prototype.getMatching = function (value) { - var res, self = this; + var self = this; if (!util.isArray(value)) { return this.tree.search(value); } else { - res = []; - value.forEach(function (v) { append(res, self.getMatching(v)); }); + var _res = {}, res = []; + + value.forEach(function (v) { + self.getMatching(v).forEach(function (doc) { + _res[doc._id] = doc; + }); + }); + + Object.keys(_res).forEach(function (_id) { + res.push(_res[_id]); + }); + return res; } }; diff --git a/test/db.test.js b/test/db.test.js index 217d142..8a28e9f 100644 --- a/test/db.test.js +++ b/test/db.test.js @@ -2479,6 +2479,15 @@ describe('Database', function () { }); // ==== End of 'Persisting indexes' ==== + it('Results of getMatching should never contain duplicates', function (done) { + d.ensureIndex({ fieldName: 'bad' }); + d.insert({ bad: ['a', 'b'] }, function () { + var res = d.getCandidates({ bad: { $in: ['a', 'b'] } }); + res.length.should.equal(1); + done(); + }); + }); + }); // ==== End of 'Using indexes' ==== // diff --git a/test/indexes.test.js b/test/indexes.test.js index fc881df..f0722ff 100644 --- a/test/indexes.test.js +++ b/test/indexes.test.js @@ -628,12 +628,16 @@ describe('Indexes', function () { }); it('Can get all documents whose key is in an array of keys', function () { + // For this test only we have to use objects with _ids as the array version of getMatching + // relies on the _id property being set, otherwise we have to use a quadratic algorithm + // or a fingerprinting algorithm, both solutions too complicated and slow given that live nedb + // indexes documents with _id always set var idx = new Index({ fieldName: 'tf' }) - , doc1 = { a: 5, tf: 'hello' } - , doc2 = { a: 2, tf: 'bloup' } - , doc3 = { a: 8, tf: 'world' } - , doc4 = { a: 7, tf: 'yes' } - , doc5 = { a: 7, tf: 'yes' } + , doc1 = { a: 5, tf: 'hello', _id: '1' } + , doc2 = { a: 2, tf: 'bloup', _id: '2' } + , doc3 = { a: 8, tf: 'world', _id: '3' } + , doc4 = { a: 7, tf: 'yes', _id: '4' } + , doc5 = { a: 7, tf: 'yes', _id: '5' } ; idx.insert(doc1);