Docs Home / mongosh / Write Scripts

Include External Files and Modules in Scripts在脚本中包含外部文件和模块

Important

A complete description of Node.js, modules, and the require() function is out of scope for this tutorial. To learn more, see the Node.js Documentation.Node.js、模块和require()函数的完整描述超出了本教程的范围。要了解更多信息,请参阅Node.js文档

To use files and modules in your mongosh interactions, use the require() function.要在mongosh交互中使用文件和模块,请使用require()函数。

In your mongosh scripts, you can require:mongosh脚本中,您可以要求:

Require a Local File需要本地文件

You can use JavaScript files in mongosh scripts without any additional setup or configuration.您可以在mongosh脚本中使用JavaScript文件,而无需任何额外的设置或配置。

Note

mongosh does not execute files imported with require(). 不执行使用require()导入的文件。Instead, mongosh adds everything from an imported file to the current execution scope.相反,mongosh会将导入文件中的所有内容添加到当前执行范围中。

Example示例

To include a file named test.js that is located in the current working directory, use one of the following commands:要包含位于当前工作目录中的名为test.js的文件,请使用以下命令之一:

require('./tests.js')
var tests = require('./tests.js')

Require a Built-In Module需要内置模块

You can require built-in Node.js modules (such as fs) in mongosh without any additional setup or configuration.您可以在mongosh中要求内置Node.js模块(如fs),而无需任何额外的设置或配置。

Example示例

The following example creates and executes a script that:以下示例创建并执行一个脚本:

  • Connects to a local deployment running on the default port.连接到在默认端口上运行的本地部署。
  • Populates the myDatabase.employees collection with sample data.用示例数据填充myDatabase.employees集合。
  • Uses the fs module to write a document from the myDatabase.employees collection to a file named employee.json.使用fs模块将myDatabase.employees集合中的文档写入名为employee.json的文件。
  1. Create a file named employee-to-text-file.js with the following contents:创建一个名为employee-to-text-file.js文件,具有以下内容:

    const fs = require('fs');

    db = connect('mongodb://localhost/myDatabase');

    db.employees.insertMany( [
    { "name": "Alice", "department": "engineering" },
    { "name": "Bob", "department": "sales" },
    { "name": "Carol", "department": "finance" }
    ] )

    const document = db.employees.findOne();

    fs.writeFileSync('employee.json', JSON.stringify(document));
  2. To load and execute the employee-to-text-file.js file, run the following command from mongosh:要加载并执行employee-to-text-file.js文件,请从mongosh运行以下命令:

    load("employee-to-text-file.js")
  3. To confirm that the data was written to the file, open the employee.json file.要确认数据已写入文件,请打开employee.json文件。

Require an npm Module需要一个npm模块

You can require Node.js modules (such as those downloaded from npm). To use external modules, you must install the modules either:您可以需要Node.js模块(例如从npm下载的模块)。要使用外部模块,您必须安装以下模块:

  • Globally
  • In the node_modules directory in your current working directory.在当前工作目录中的node_modules目录中。

There are two packaging standards for Node.js modules.Node.js模块有两种打包标准。

Packaging Standard包装标准Works with require()使用require()
CommonJS (CJS)Yes
ECMAScript Module (ES Module)No

You cannot require() an ES module in mongosh. If you want to use functionality from an ES module, check to see if there is a CommonJS version that you can use instead. For more information, see:你不能在mongoshrequire()一个ES模块。如果你想使用ES模块的功能,请检查是否有可以使用的CommonJS版本。有关更多信息,请参阅:

Tip

You can require remote npm modules using this construction:您可以使用以下构造要求远程npm模块:

const localRequire = require('module').createRequire(__filename);

For an example, see index.js in the resumetoken snippet.例如,请参阅resumethoken代码片段中的index.js

Example示例

Important

To run this example, you must install the date-fns module either globally or in the node_modules directory in your current working directory.要运行此示例,您必须全局或在当前工作目录的node_modules目录中安装date-fns模块。

The following example creates and executes a script that:以下示例创建并执行一个脚本:

  • Connects to a local deployment running on the default port.连接到在默认端口上运行的本地部署。
  • Populates the myDatabase.cakeSales collection with sample data.用示例数据填充myDatabase.cakeSales集合。
  • Uses the date-fns module to format dates.使用date-fns模块设置日期格式。
  1. Create a file named date-fns-formatting.js with the following contents:创建一个名为date-fns-formatting.js的文件,内容如下:

    const formatDistance = require('date-fns/formatDistance')

    db = connect('mongodb://localhost/myDatabase');

    db.cakeSales.insertMany( [
    { _id: 0, type: "chocolate", orderDate: new Date("2020-05-18T14:10:30Z"),
    state: "CA", price: 13, quantity: 120 },
    { _id: 1, type: "chocolate", orderDate: new Date("2021-03-20T11:30:05Z"),
    state: "WA", price: 14, quantity: 140 },
    { _id: 2, type: "vanilla", orderDate: new Date("2021-01-11T06:31:15Z"),
    state: "CA", price: 12, quantity: 145 },
    { _id: 3, type: "vanilla", orderDate: new Date("2020-02-08T13:13:23Z"),
    state: "WA", price: 13, quantity: 104 },
    { _id: 4, type: "strawberry", orderDate: new Date("2019-05-18T16:09:01Z"),
    state: "CA", price: 41, quantity: 162 },
    { _id: 5, type: "strawberry", orderDate: new Date("2019-01-08T06:12:03Z"),
    state: "WA", price: 43, quantity: 134 }
    ] )

    const saleDate0 = db.cakeSales.findOne( { _id: 0 } ).orderDate
    const saleDate1 = db.cakeSales.findOne( { _id: 1 } ).orderDate

    const saleDateDistance0 = formatDistance(saleDate0, new Date(), { addSuffix: true })
    const saleDateDistance1 = formatDistance(saleDate1, new Date(), { addSuffix: true })

    print("{ _id: 0 } orderDate was " + saleDateDistance0)
    print("{ _id: 1 } orderDate was " + saleDateDistance1)
  2. To load and execute the date-fns-formatting.js file, run the following command from mongosh:要加载并执行date-fns-formatting.js文件,请从mongosh运行以下命令:

    load("date-fns-formatting.js")

    mongosh outputs something like the following:输出如下内容:

    { _id: 0 } orderDate was over 1 year ago
    { _id: 1 } orderDate was 7 months ago

    Your output may vary depending on the date that you run the example.输出可能因运行示例的日期而异。