Mongoengine 简明教程
MongoEngine - Javascript
MongoEngine 的 QuerySet 对象具有 exec_js() 方法,该方法允许在 MongoDB 服务器上执行 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().
请注意,MongoEngine 文档类中的属性在数据库中使用不同的名称(使用 Field 构造函数中的 db_field 关键字参数设置)。
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')
为此,存在一种机制,可以在 Javascript 代码中将 MongoEngine 字段属性替换为数据库字段名。
For this purpose, a mechanism exists for replacing MongoEngine field attribute with the database field names in Javascript code.
当在集合对象中访问一个字段时,请使用方括号符号,并在 MongoEngine 字段名前加上一个波形符号 (~)。波形符号后的字段名将转换为在数据库中使用的名称。
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];
请注意,当 Javascript 代码引用嵌入式文档中的字段时,应在嵌入式文档中的字段名之前使用嵌入式文档字段的名称,后跟一个点。
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.