Use require() to Include External Modules

On this page本页内容

Note
Preview

MongoDB for VS Code is currently available as a Preview in the Visual Studio Marketplace. The product, its features, and the corresponding documentation may change during the Preview stage.

Important

A complete description of Node.js, modules, and the require() function is out of scope for this tutorial. To learn more, refer to the Node.js Documentation.

You can use the require() function in your MongoDB Playgrounds to include modules which exist in separate files.

You can require() native Node modules (such as fs) in your Playground without any additional setup or configuration.

Example

The following Playground uses the fs module to write a document from the test.employees collection to a file named employee.txt:

const fs = require('fs');
use("test");
const document = db.employees.findOne();
fs.writeFileSync('employee.txt', JSON.stringify(document));

To require() non-native Node modules (such as those downloaded from npm) you must install the module in one of the following folders based on your operating system:

Operating System Module Location
macOS and Linux

One of either:

  • $HOME/.node_modules
  • $HOME/node_modules
  • $HOME/.vscode/extensions/node_modules
  • $HOME/.vscode/extensions/mongodb.mongodb-vs-code-<version>\node_modules
Windows

One of either:

  • C:\Users\.node_modules
  • C:\Users\node_modules
  • C:\Users\<user>\node_modules
  • C:\Users\<user>\.vscode\extensions\node_modules
  • C:\Users\<user>\.vscode\extensions\mongodb.mongodb-vscode-<version>\node_modules

Once you install or copy your desired package to one of the module directories, you can require() that package.

Example

The following Playground uses the moment package to write the current date to a file called date.txt:

const moment = require('moment');
const fs = require('fs');
const currentDate = moment().format("MMMM DD YYYY");
fs.writeFileSync('date.txt', currentDate);
Run Aggregation PipelinesCreate an Atlas Cluster from a Template using Terraform