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脚本中,您可以要求:
- Local files
Built-in Node.js modules内置Node.js模块External (npm) Node.js modules外部(npm)Node.js模块
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.employeescollection with sample data.myDatabase.employees集合。Uses the使用fsmodule to write a document from themyDatabase.employeescollection to a file namedemployee.json.fs模块将myDatabase.employees集合中的文档写入名为employee.json的文件。
Create a file named创建一个名为employee-to-text-file.jswith 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));To load and execute the要加载并执行employee-to-text-file.jsfile, run the following command frommongosh:employee-to-text-file.js文件,请从mongosh运行以下命令:load("employee-to-text-file.js")To confirm that the data was written to the file, open the要确认数据已写入文件,请打开employee.jsonfile.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_modulesdirectory in your current working directory.node_modules目录中。
There are two packaging standards for Node.js modules.Node.js模块有两种打包标准。
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:mongosh中require()一个ES模块。如果你想使用ES模块的功能,请检查是否有可以使用的CommonJS版本。有关更多信息,请参阅:
Tip
Example示例
Important
The following example creates and executes a script that:以下示例创建并执行一个脚本:
Connects to a local deployment running on the default port.连接到在默认端口上运行的本地部署。Populates the用示例数据填充myDatabase.cakeSalescollection with sample data.myDatabase.cakeSales集合。Uses the date-fns module to format dates.使用date-fns模块设置日期格式。
Create a file named创建一个名为date-fns-formatting.jswith 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)To load and execute the要加载并执行date-fns-formatting.jsfile, run the following command frommongosh:date-fns-formatting.js文件,请从mongosh运行以下命令:load("date-fns-formatting.js")mongoshoutputs something like the following:输出如下内容:{ _id: 0 } orderDate was over 1 year ago
{ _id: 1 } orderDate was 7 months agoYour output may vary depending on the date that you run the example.输出可能因运行示例的日期而异。