MongoEngine – Javascript

MongoEngine – Javascript

QuerySet object of MongoEngine has exec_js() method that allows execution of a Javascript function on MongoDB server. This function processes the following arguments −

exec_js(code, *field_names, **options)

Where,

  • code − a string containing Javascript code to execute
  • fields − to be used in your function, which will be passed as arguments
  • options − options that you want available to the function (accessed in Javascript through the options object)
    In addition, some more variables are also made available to the function’s scope as given below −
  • collection − name of the collection corresponding to the Document class. This should be used to get the Collection object from db in Javascript code.
  • query − the query that has been generated by the QuerySet object; passed into the find() method on a Collection object in the Javascript function.
  • options − an object containing the keyword arguments passed into exec_js().
    Note that attributes in MongoEngine document class may use different names in the database (set using the db_field keyword argument to a Field constructor).

    from mongoengine import connect
    from mongoengine import StringField, IntField, Document, DecimalField, ListField
    connect('mydata', host='mongodb://localhost/mydata')
    class Books(Document):
    title = StringField(db_field='doctitle')

    For this purpose, a mechanism exists for replacing MongoEngine field attribute with the database field names in Javascript code.
    When accessing a field on a collection object, use square-bracket notation, and prefix the MongoEngine field name with a tilde (~) symbol. The field name that follows the tilde will be translated to the name used in the database.

    document': doc[~title];

    Note that when Javascript code refers to fields on embedded documents, the name of the EmbeddedDocumentField, followed by a dot, should be used before the name of the field on the embedded document.

MongoEngine – Atomic Updates (Prev Lesson)
(Next Lesson) MongoEngine – GridFS
', { 'anonymize_ip': true });