diff --git a/lib/model.js b/lib/model.js index edf121d..04691d3 100644 --- a/lib/model.js +++ b/lib/model.js @@ -288,12 +288,11 @@ function getDotValue (obj, field) { /** * Test for field equality - * @param {Object} obj The model to check - * @param {String} field Can contain dots, in that case that means we will set a subfield recursively - * @param {Model} value + * @param {Object} objValue The value from the object to check + * @param {Model} value The value from the query to check against */ -matcherFunctions.$eq = function (obj, field, value) { - return areThingsEqual(getDotValue(obj, field), value); +matcherFunctions.$eq = function (objValue, value) { + return areThingsEqual(objValue, value); }; @@ -302,10 +301,21 @@ matcherFunctions.$eq = function (obj, field, value) { */ function match (obj, query) { var match = true + , objValue, arrayMatch , i, k; Object.keys(query).forEach(function (k) { - if (!matcherFunctions.$eq(obj, k, query[k])) { match = false; } + objValue = getDotValue(obj, k); + + if (util.isArray(objValue)) { + arrayMatch = false; // We only need one match in the array for a success + for (i = 0; i < objValue.length; i += 1) { + if (matcherFunctions.$eq(objValue[i], query[k])) { arrayMatch = true; } + } + match = match && arrayMatch; + } else { + if (!matcherFunctions.$eq(objValue, query[k])) { match = false; } + } }); return match; diff --git a/test/db.test.js b/test/db.test.js index ae4eca4..aa5ac1e 100644 --- a/test/db.test.js +++ b/test/db.test.js @@ -284,6 +284,35 @@ describe('Database', function () { }); }); + it('Array fields match if any element matches', function (done) { + d.insert({ fruits: ['pear', 'apple', 'banana'] }, function (err, doc1) { + d.insert({ fruits: ['coconut', 'orange', 'pear'] }, function (err, doc2) { + d.insert({ fruits: ['banana'] }, function (err, doc3) { + d.find({ fruits: 'pear' }, function (err, docs) { + assert.isNull(err); + docs.length.should.equal(2); + _.pluck(docs, '_id').should.contain(doc1._id); + _.pluck(docs, '_id').should.contain(doc2._id); + + d.find({ fruits: 'banana' }, function (err, docs) { + assert.isNull(err); + docs.length.should.equal(2); + _.pluck(docs, '_id').should.contain(doc1._id); + _.pluck(docs, '_id').should.contain(doc3._id); + + d.find({ fruits: 'doesntexist' }, function (err, docs) { + assert.isNull(err); + docs.length.should.equal(0); + + done(); + }); + }); + }); + }); + }); + }); + }); + }); // ==== End of 'Find' ==== //