Able to test array fields

pull/2/head
Louis Chatriot 12 years ago
parent 1481e1ca88
commit 11e2510d9a
  1. 22
      lib/model.js
  2. 29
      test/db.test.js

@ -288,12 +288,11 @@ function getDotValue (obj, field) {
/** /**
* Test for field equality * Test for field equality
* @param {Object} obj The model to check * @param {Object} objValue The value from the object to check
* @param {String} field Can contain dots, in that case that means we will set a subfield recursively * @param {Model} value The value from the query to check against
* @param {Model} value
*/ */
matcherFunctions.$eq = function (obj, field, value) { matcherFunctions.$eq = function (objValue, value) {
return areThingsEqual(getDotValue(obj, field), value); return areThingsEqual(objValue, value);
}; };
@ -302,10 +301,21 @@ matcherFunctions.$eq = function (obj, field, value) {
*/ */
function match (obj, query) { function match (obj, query) {
var match = true var match = true
, objValue, arrayMatch
, i, k; , i, k;
Object.keys(query).forEach(function (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; return match;

@ -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' ==== // }); // ==== End of 'Find' ==== //

Loading…
Cancel
Save