Mongodb $where query always true with nodejs

后端 未结 7 2164
隐瞒了意图╮
隐瞒了意图╮ 2021-01-12 11:01

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



        
7条回答
  •  半阙折子戏
    2021-01-12 11:28

    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.

提交回复
热议问题