Docs Menu
Docs Home
/
MongoDB for VS Code
/ /

Use require() to Load Local Files

On this page

  • About this Task
  • Steps
  • Results
  • Learn More

You can use the require() function in your MongoDB Playgrounds to include code from local files. You can store your code in a single location and reuse that code in different playgrounds.

This tutorial shows how to use require() to load local scripts. You can also use require() to load Node modules, like those downloaded from npm. For more information, see Use require() to Include Node.js Modules.

1

The following script file validates documents to ensure that the required fields are present. Save the script to your local filesystem as validate.js:

// validate.js
const required_fields = [ 'name', 'email' ]
const validate_data = (document) => {
let is_valid = true;
for (const field of required_fields) {
if (document[field] == null) {
is_valid = false;
}
};
return is_valid;
};
module.exports = validate_data;
2

The following playground uses require() to call the validate_data function specified in validate.js. The validate_data function is called on two sample documents. If the document contains the required fields name and email, it is inserted into the people collection.

Important

Update the first line of the playground with the path to the validate.js file:

// playground-1.mongodb.js
const validate = require('/path/to/validate.js');
use('mongodbVSCodePlaygroundDB');
const doc1 = { _id: 1, 'name': 'Taylor', 'email': 't123@gmail.com' };
const doc2 = { _id: 2, 'name': 'Taylor' };
const docs = [ doc1, doc2 ];
let inserted_count = 0;
for (const doc of docs) {
if (validate(doc)) {
db.getCollection('people').insertOne(doc);
inserted_count++;
}
};
console.log("Inserted " + inserted_count + " documents");
3

To run your Playground, press the Play Button at the top right of the Playground View. MongoDB for VS Code splits your Playground and outputs the results of your Playground in the Playground Results.json pane. If you disabled split-view, MongoDB for VS Code outputs the results of your Playground in a new tab.

Only doc1 contains both required fields and is inserted into the collection. doc2 does not contain the required field email, and is not inserted.

To confirm that the correct document was inserted, query the people collection:

use mongodbVSCodePlaygroundDB
db.people.find()

Output:

[
{ _id: 1, name: 'Taylor', email: 't123@gmail.com' }
]

Back

Use require() to Include Node.js Modules

Next

Create an