Docs Home → Develop Applications → MongoDB Manual
Store a JavaScript Function on the Server在服务器上存储JavaScript函数
Do not store application logic in the database. 不要将应用程序逻辑存储在数据库中。There are performance limitations to running JavaScript inside of MongoDB. Application code also is typically most effective when it shares version control with the application itself.在MongoDB内部运行JavaScript存在性能限制。当应用程序代码与应用程序本身共享版本控制时,应用程序代码通常也是最有效的。
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; }
}
);
The_id
field holds the name of the function and is unique per database._id
字段包含函数的名称,并且每个数据库都是唯一的。The值字段保存函数定义。value
field holds the function definition.
These functions, saved as BSON type, are available for use from any JavaScript context, such as 这些函数保存为BSON类型,可从任何JavaScript上下文中使用,如mapReduce
and $where
.mapReduce
和$where
。
Functions saved as the deprecated BSON type JavaScript (with scope), however, cannot be used by 然而,保存为不推荐使用的BSON类型JavaScript(带范围)的函数不能由MongoDB 4.4中的mapReduce
and $where
starting in MongoDB 4.4.mapReduce
和$where
使用。