Mongodb $where query always true with nodejs
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.