Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-60770

$function does not accept native functions

    • Type: Icon: Bug Bug
    • Resolution: Unresolved
    • Priority: Icon: Minor - P4 Minor - P4
    • None
    • Affects Version/s: 5.0.3
    • Component/s: None
    • Labels:
    • Query Execution
    • ALL

      For the following pipeline:

      db.listings.updateMany({}, [{ $set: { "host_verifications": { $function: {args: ["$host_verifications"], lang: "js", body: JSON.parse } } } }])

      the "$function" operator does not seem to work correctly and returns a rather hard to decipher error: "MongoServerError: SyntaxError: missing ] after element list" . JSON.parse is a widely used function and certainly a valid one for lang type "js". The problem here is that instead of treating  functions as first-class functions (the way Javascript does it) and being able to pass them as an argument Mongo seems to call toString() method instead. For this particular function calling toString() returns: "function parse() { [native code] }" which inserted into the pipeline as body yields the same error.

      There is a possible workaround for this:

      body: function(x){return JSON.parse(x);}

      Here the server has no issues with calling native code function.

      Looks like little extra logic should be able to handle such cases even if hard to fix in the core. Making the error message more readable would certainly help as well. 

            backlog-query-execution [DO NOT USE] Backlog - Query Execution
            wojciech.waga@gmail.com Wojciech Waga
            0 Vote for this issue
            5 Start watching this issue