Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix issue #49 - $where operator is not evaluated last #50

Merged
merged 3 commits into from
Jun 22, 2017
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion mingo.js
Original file line number Diff line number Diff line change
Expand Up @@ -1327,10 +1327,15 @@ Mingo.Query.prototype = {

assert(isObject(this.__criteria), 'Criteria must be of type Object')

var whereOperator;

for (var field in this.__criteria) {
if (has(this.__criteria, field)) {
var expr = this.__criteria[field]
if (inArray(['$and', '$or', '$nor', '$where'], field)) {
// save $where operators to be executed after other operators
if ('$where' === field) {
whereOperator = {field: field, expr: expr};
} else if (inArray(['$and', '$or', '$nor'], field)) {
this._processOperator(field, field, expr)
} else {
// normalize expression
Expand All @@ -1342,6 +1347,11 @@ Mingo.Query.prototype = {
}
}
}

if(whereOperator) {
this._processOperator(whereOperator.field, whereOperator.field, whereOperator.expr);
}

}
},

Expand Down
48 changes: 48 additions & 0 deletions test/collections.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,51 @@ test('Match $all with $elemMatch on nested elements', function (t) {
var result = Mingo.find(data, criteria).count()
t.ok(result === 1, 'can match using $all with $elemMatch on nested elements')
})

test('Evaluate $where last', function (t) {
t.plan(2)

var data = [
{
user: {
username: 'User1',
projects: [
{name: 'Project 1', rating: {complexity: 6}},
{name: 'Project 2', rating: {complexity: 2}}
],
color: 'green',
number: 42
}
},
{
user: {
username: 'User2',
projects: [
{name: 'Project 1', rating: {complexity: 6}},
{name: 'Project 2', rating: {complexity: 8}}
]
}
}
]

var criteria = {
'user.color': {$exists: true},
'user.number': {$exists: true},
$where: 'this.user.color === "green" && this.user.number === 42'
}
// It should return one user object
var result = Mingo.find(data, criteria).count()
t.ok(result === 1, 'can safely reference properties on this using $where and $exists')

criteria = {
'user.color': {$exists: true},
'user.number': {$exists: true},
$and: [
{ $where: 'this.user.color === "green"' },
{ $where: 'this.user.number === 42' }
]
}
// It should return one user object
var result = Mingo.find(data, criteria).count()
t.ok(result === 1, 'can safely reference properties on this using multiple $where operators and $exists')
})