Docs Menu

Docs HomeDevelop ApplicationsMongoDB for VS Code

Use require() to Include External Modules

On this page

  • Require Native Modules
  • Require Non-Native Modules

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));

Tip

See also:

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);
←  Export a Query or Pipeline to LanguageCreate an Atlas Cluster from a Template using Terraform →