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. 在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; }
   }
);

These functions, saved as BSON type JavaScript, are available for use from any JavaScript context, such as mapReduce and $where.这些函数保存为BSON类型的JavaScript,可以在任何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.但是,从MongoDB 4.4开始的mapReduce$where不能使用保存为不推荐使用的BSON类型JavaScript(具有作用域)的函数。