Docs HomeDevelop ApplicationsMongoDB Manual

Store a JavaScript Function on the Server在服务器上存储JavaScript函数

Note

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 mapReduce and $where.这些函数保存为BSON类型,可从任何JavaScript上下文中使用,如mapReduce$where

Functions saved as the deprecated BSON type JavaScript (with scope), however, cannot be used by mapReduce and $where starting in MongoDB 4.4.然而,保存为不推荐使用的BSON类型JavaScript(带范围)的函数不能由MongoDB 4.4中的mapReduce$where使用。