Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb $where query always true with nodejs

When I query my database with a function passed in the "$where" clause in nodejs, it always return me all documents in the db.

For example, if I do

var stream = timetables.find({$where: function() { return false; }}).stream();

it return me all the documents. Instead, if I do

var stream = timetables.find({$where: 'function() { return false; }'}).stream();

the function is really executed, and this code doesn't return any document.

The problem is that if I convert in string my function the context's bindinds are removed, and I need them for more complex query. For example:

var n = 1;
var f = function() { return this.number == n; }
var stream = timetables.find({$where: f.toString()}).stream();
// error: n is not defined

Is this a normal behaviour? How can I solve my problem? Please excuse me for my poor english!

like image 897
Duma - Stefano Gombi Avatar asked Mar 25 '13 10:03

Duma - Stefano Gombi


1 Answers

First off, keep in mind that the $where operator should almost never be used for the reasons explained here (credit goes to @WiredPrairie).

Back to your issue, the approach you'd like to take won't work even in the mongodb shell (which explicitly allows naked js functions with the $where operator). The javascript code provided to the $where operator is executed on the mongo server and won't have access to the enclosing environment (the "context bindings").

> db.test.insert({a: 42})
> db.test.find({a: 42})
{ "_id" : ObjectId("5150433c73f604984a7dff91"), "a" : 42 }
> db.test.find({$where: function() { return this.a == 42 }}) // works
{ "_id" : ObjectId("5150433c73f604984a7dff91"), "a" : 42 }
> var local_var = 42
> db.test.find({$where: function() { return this.a == local_var }})
error: {
    "$err" : "error on invocation of $where function:\nJS Error: ReferenceError: local_var is not defined nofile_b:1",
    "code" : 10071
}

Moreover it looks like that the node.js native mongo driver behaves differently from the shell in that it doesn't automatically serialize a js function you provide in the query object and instead it likely drops the clause altogether. This will leave you with the equivalent of timetables.find({}) which will return all the documents in the collection.

like image 188
Utaal Avatar answered Oct 21 '22 15:10

Utaal