'Execute a Javascript function on the server. A list of fields may be
provided, which will be translated to their correct names and supplied
as the arguments to the function. A few extra variables are added to
the function\'s scope: ``collection``, which is the name of the
collection in use; ``query``, which is an object representing the
current query; and ``options``, which is an object containing any
options specified as keyword arguments.
As fields in MongoEngine may use different names in the database (set
using the :attr:`db_field` keyword argument to a :class:`Field`
constructor), a mechanism exists for replacing MongoEngine field names
with the database field names in Javascript code. When accessing a
field, use square-bracket notation, and prefix the MongoEngine field
name with a tilde (~).
:param code: a string of Javascript code to execute
:param fields: fields that you will be using in your function, which
will be passed in to your function as arguments
:param options: options that you want available to the function
(accessed in Javascript through the ``options`` object)'

def exec_js(self, code, *fields, **options):

    queryset = self.clone()
    code = queryset._sub_js_fields(code)
    fields = [queryset._document._translate_field_name(f) for f in fields]
    collection = queryset._document._get_collection_name()
    scope = {'collection': collection, 'options': (options or {})}
    query = queryset._query
    if queryset._where_clause:
        query['$where'] = queryset._where_clause
    scope['query'] = query
    code = Code(code, scope=scope)
    db = queryset._document._get_db()
    return db.eval(code, *fields)
