From 2f2b9ab58fbc54249187c3280271ff49c5bbbd71 Mon Sep 17 00:00:00 2001 From: Louis Chatriot Date: Sat, 22 Jun 2013 18:11:07 +0200 Subject: [PATCH] Implemented comparator --- lib/model.js | 14 ++++++++++++++ test/model.test.js | 20 +++++++++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/lib/model.js b/lib/model.js index 16e1016..ba70bf2 100644 --- a/lib/model.js +++ b/lib/model.js @@ -503,6 +503,20 @@ comparisonFunctions.$nin = function (a, b) { return !comparisonFunctions.$in(a, b); }; +comparisonFunctions.$exists = function (value, exists) { + if (exists || exists === '') { // This will be true for all values of exists except false, null, undefined and 0 + exists = true; // That's strange behaviour (we should only use true/false) but that's the way Mongo does it... + } else { + exists = false; + } + + if (value === undefined) { + return !exists + } else { + return exists; + } +}; + /** * Match any of the subqueries diff --git a/test/model.test.js b/test/model.test.js index 44ed540..ad02e57 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -770,7 +770,7 @@ describe('Model', function () { // General behaviour is tested in the block about $lt. Here we just test operators work - describe('Other comparison operators: $lte, $gt, $gte, $ne, $in', function () { + describe('Other comparison operators: $lte, $gt, $gte, $ne, $in, $exists', function () { it('$lte', function () { model.match({ a: 5 }, { a: { $lte: 6 } }).should.equal(true); @@ -819,6 +819,24 @@ describe('Model', function () { (function () { model.match({ a: 5 }, { a: { $in: 5 } }); }).should.throw(); }); + it('$exists', function () { + model.match({ a: 5 }, { a: { $exists: 1 } }).should.equal(true); + model.match({ a: 5 }, { a: { $exists: true } }).should.equal(true); + model.match({ a: 5 }, { a: { $exists: new Date() } }).should.equal(true); + model.match({ a: 5 }, { a: { $exists: '' } }).should.equal(true); + model.match({ a: 5 }, { a: { $exists: [] } }).should.equal(true); + model.match({ a: 5 }, { a: { $exists: {} } }).should.equal(true); + + model.match({ a: 5 }, { a: { $exists: 0 } }).should.equal(false); + model.match({ a: 5 }, { a: { $exists: false } }).should.equal(false); + model.match({ a: 5 }, { a: { $exists: null } }).should.equal(false); + model.match({ a: 5 }, { a: { $exists: undefined } }).should.equal(false); + + model.match({ a: 5 }, { b: { $exists: true } }).should.equal(false); + + model.match({ a: 5 }, { b: { $exists: false } }).should.equal(true); + }); + });