diff --git a/lib/model.js b/lib/model.js index cdfb512..47e66a0 100644 --- a/lib/model.js +++ b/lib/model.js @@ -302,26 +302,38 @@ matcherFunctions.$eq = function (objValue, value) { * @param {Object} query */ function match (obj, query) { - var match = true - , objValue, arrayMatch - , i, k; + var queryKeys = Object.keys(query) + , i + ; - Object.keys(query).forEach(function (k) { - objValue = getDotValue(obj, k); + for (i = 0; i < queryKeys.length; i += 1) { + if (!matchQueryKey(obj, query, queryKeys[i])) { return false; } + } - 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 true; +}; + + +/** + * Match a specific key of a given query + */ +function matchQueryKey (obj, query, queryKey) { + var objValue = getDotValue(obj, queryKey) + , queryValue = query[queryKey] + , i + ; + + if (util.isArray(objValue)) { + for (i = 0; i < objValue.length; i += 1) { + if (matcherFunctions.$eq(objValue[i], queryValue)) { return true; } } - }); + return false; + } else { + if (!matcherFunctions.$eq(objValue, queryValue)) { return false; } + } - return match; -}; + return true; +} // Interface diff --git a/test/model.test.js b/test/model.test.js index c8140ea..69a1ac8 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -416,6 +416,9 @@ describe('Model', function () { model.match({ tags: ['node', 'js', 'db'] }, { tags: 'python' }).should.equal(false); model.match({ tags: ['node', 'js', 'db'] }, { tags: 'js' }).should.equal(true); model.match({ tags: ['node', 'js', 'db'] }, { tags: 'js', tags: 'node' }).should.equal(true); + + // Mixed matching with array and non array + model.match({ tags: ['node', 'js', 'db'], nedb: true }, { tags: 'js', nedb: true }).should.equal(true); }); });