Do not store application logic in the database. 不要在数据库中存储应用程序逻辑。There are performance limitations to running JavaScript inside of MongoDB. 在MongoDB内部运行JavaScript存在性能限制。Application code also is typically most effective when it shares version control with the application itself.应用程序代码通常在与应用程序本身共享版本控制时最有效。
There is a special system collection named 有一个名为system.js
that can store JavaScript functions for reuse.system.js
的特殊系统集合,可以存储JavaScript函数以供重用。
To store a function, you can use the 要存储函数,可以使用db.collection.insertOne()
, as in the following examples:db.collection.insertOne()
,如以下示例所示:
db.system.js.insertOne( { _id: "echoFunction", value : function(x) { return x; } } ); db.system.js.insertOne( { _id : "myAddFunction" , value : function (x, y){ return x + y; } } );
_id
field holds the name of the function and is unique per database._id
字段包含函数的名称,每个数据库都是唯一的。value
field holds the function definition.value
字段保存函数定义。These functions, saved as BSON type JavaScript, are available for use from any JavaScript context, such as 这些函数保存为BSON类型的JavaScript,可以在任何JavaScript上下文中使用,例如mapReduce
and $where
.mapReduce
和$where
。
Functions saved as the deprecated BSON type JavaScript (with scope), however, cannot be used by 但是,从MongoDB 4.4开始的mapReduce
and $where
starting in MongoDB 4.4.mapReduce
和$where
不能使用保存为不推荐使用的BSON类型JavaScript(具有作用域)的函数。