Mongodb $where query always true with nodejs

后端 未结 7 1983
隐瞒了意图╮
隐瞒了意图╮ 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:22

    You can use a wrapper to pass basic JSON objects, ie. (pardon coffee-script):

    # That's the main wrapper.
    wrap = (f, args...) ->
      "function() { return (#{f}).apply(this, #{JSON.stringify(args)}) }"
    
    # Example 1
    where1 = (flag) ->
      @myattr == 'foo' or flag
    
    # Example 2 with different arguments
    where2 = (foo, options = {}) ->
      if foo == options.bar or @_id % 2 == 0
        true
      else
        false
    
    db.collection('coll1').count $where: wrap(where1, true), (err, count) ->
      console.log err, count
    
    db.collection('coll1').count $where: wrap(where2, true, bar: true), (err, count) ->
      console.log err, count
    

    Your functions are going to be passed as something like:

    function () {
        return (function (flag) {
            return this.myattr === 'foo' || flag;
        }).apply(this, [true])
    }
    

    ...and example 2:

    function () {
        return (
            function (foo, options) {
                if (options == null) {
                    options = {};
                }
                if (foo === options.bar || this._id % 2 === 0) {
                    return true;
                } else {
                    return false;
                }
            }
        ).apply(this, [ true, { "bar": true } ])
    }
    

提交回复
热议问题