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
(self, code, *fields, **options)
| 1507 | ) |
| 1508 | |
| 1509 | def exec_js(self, code, *fields, **options): |
| 1510 | """Execute a Javascript function on the server. A list of fields may be |
| 1511 | provided, which will be translated to their correct names and supplied |
| 1512 | as the arguments to the function. A few extra variables are added to |
| 1513 | the function's scope: ``collection``, which is the name of the |
| 1514 | collection in use; ``query``, which is an object representing the |
| 1515 | current query; and ``options``, which is an object containing any |
| 1516 | options specified as keyword arguments. |
| 1517 | |
| 1518 | As fields in MongoEngine may use different names in the database (set |
| 1519 | using the :attr:`db_field` keyword argument to a :class:`Field` |
| 1520 | constructor), a mechanism exists for replacing MongoEngine field names |
| 1521 | with the database field names in Javascript code. When accessing a |
| 1522 | field, use square-bracket notation, and prefix the MongoEngine field |
| 1523 | name with a tilde (~). |
| 1524 | |
| 1525 | :param code: a string of Javascript code to execute |
| 1526 | :param fields: fields that you will be using in your function, which |
| 1527 | will be passed in to your function as arguments |
| 1528 | :param options: options that you want available to the function |
| 1529 | (accessed in Javascript through the ``options`` object) |
| 1530 | """ |
| 1531 | queryset = self.clone() |
| 1532 | |
| 1533 | code = queryset._sub_js_fields(code) |
| 1534 | |
| 1535 | fields = [queryset._document._translate_field_name(f) for f in fields] |
| 1536 | collection = queryset._document._get_collection_name() |
| 1537 | |
| 1538 | scope = {"collection": collection, "options": options or {}} |
| 1539 | |
| 1540 | query = queryset._query |
| 1541 | if queryset._where_clause: |
| 1542 | query["$where"] = queryset._where_clause |
| 1543 | |
| 1544 | scope["query"] = query |
| 1545 | code = Code(code, scope=scope) |
| 1546 | |
| 1547 | db = queryset._document._get_db() |
| 1548 | return db.command("eval", code, args=fields).get("retval") |
| 1549 | |
| 1550 | def where(self, where_clause): |
| 1551 | """Filter ``QuerySet`` results with a ``$where`` clause (a Javascript |