This repository contains an example application that connects to MongoDB Atlas using the Node.js MongoDB driver. You can use this application as a reference for when you build your Node.js application.
To build and run this project, you need Node.js version 10 or later and a compatible version of NPM (Node Package Manager) installed. For information on how to check your version of Node and NPM, see the NPMJS page on downloading and installing Node.js and npm.
The following instructions explain how to get your project connected to your instance of MongoDB Atlas.
To get started with this sample project, download this repository to your programming environment. You can clone this project using Git version control:
git clone https://github.com/mongodb-university/atlas_starter_nodejs.git
Or you can download the ZIP archive using your browser. If you download this project as a ZIP archive, unzip the archive before proceeding.
Navigate to the directory containing the project in your shell or open it in your preferred IDE.
Then, use the NPM dependency file that we included in the project
directory called package.json
to download and install your dependencies:
npm install
This command reads the package.json
file and downloads and saves the
dependencies defined within it to a directory called node_modules
. It
also creates a package-lock.json
file that sets the version information for
each of the modules required to build your project.
At this point, you should have appropriate versions of Node.js and NPM installed as well as a project directory that contains the dependencies you need to use the Node.js MongoDB driver.
-
Open the
app.js
file. -
Search for the variable
uri
near the top which is assigned placeholder text. Replace the placeholder text with the connection string for your Atlas cluster. For more information on finding the connection string, see Connect via Driver in the Atlas documentation.
const uri =
"<Your Atlas Connection String>";
- Save the changes to your
app.js
file.
If you are running from the shell, you can run the application from the directory that contains it with the following command:
node app
If you are running it from the IDE, use the appropriate command to run the
contents of the app.js
file.
- Click the Run icon, or from the Run menu, choose Start Debugging.
Assuming you have the correct connection string, you have now connected the Node app to your MongoDB Atlas datastore. Have fun modifying the code to experiment with the Node driver and MongoDB.
Are you having trouble getting connected to your MongoDB Atlas instance? Double-check the following:
-
Have you replaced the
uri
variable with a valid connection string provided by the Atlas UI? Read more here for further context. -
Have you added your current IP address to the access list in the Atlas UI?