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).


class BlogPost(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.

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *