We are going to create a database that stores all the data and other information related to our application.
To do this, we will use the Atlas service to create a MongoDB database in the cloud.
MongoDB is a non-SQL database that is well-suited for building modern applications. It stores data in the form of documents, rather than using traditional tables. Atlas makes it easy to set up a database in the cloud, and it also takes care of security and other technical details so you don't have to worry about them. Plus, it offers a free tier that you can use.
First, we will create the database on the Atlas website, and then we will connect to it through the application.
Let's get started!
First, you'll need to log into the Atlas website or signup for a free account if you haven't already.
After successfully logging in or signing up, navigate to the create a cluster page. The page should look similar to the image below.
To begin with, choose the FREE option on the right-hand side.
This will give you plenty of horsepower to start with and you can easily upgrade your Cluster to something more powerful down the line when you need it.
This will redirect you to a page where you can choose some configuration settings for your server.
The first option is the cloud provider and region, which is the location of the server housing your database. Choose the option that is in the closest geographic proximity to where your visitors will be physically located. The closer a request is to the server, the faster it will be fulfilled.
You can choose from a set of cluster tiers with different storage and bandwidth capabilities at the bottom.
Ensure that the FREE option is selected before proceeding, give your cluster a name that will be displayed in your account control panel or you can skip the "Additional Settings" section.
Finally, hit Create Cluster button.
It will take a few minutes for Atlas to create the cluster in their system.
When the process is complete, you should see your new database cluster on a page that looks like below.
Before we can use the new database for anything, we need to first secure it by adding your IP address to the connection white list and then create a MongoDB username and password for the database.
We first click on the Database in the sidebar dashboard area, then hit Connect button.
This will open a dialog box that will guide you through configuring some security settings for the database.
Click on the Add Your Current IP Address button and verify that Atlas has populated the input field with the correct IP address matching your local development machine.
If you want to allow connections from any IP address, set the IP address value to 0.0.0.0 then click Add IP Address
Fill out a username and password and hit "Create Database User" button to generate the new user. These are the credentials you'll use to read and write data to and from the database.
Next, click on the Choose a connection method button to move on to the next step.
Since we'll be connecting to our database via our NodeJS REST API, we want the "Connect your application" option.
When you click on that option, a page will be displayed where Atlas generates a connection string you can copy and paste into your application.
Make sure Node.js is selected as the coding language driver. In the second section, a connection string should be generated for you.
Copy that connection string to your clipboard or keep the browser page open so you can come back to it. We'll use that string in the next step.
Now we need to add some code to the application to facilitate the interaction between the application and the MongoDB database we just created in the cloud using Atlas.
We'll be using the Mongoose NPM package to help us manage our MongoDB data and schemas. Therefore, we need to install it into the project's dependencies.
Execute this command inside the /api
directory:
npm i mongoose
Now we can require()
and use the mongoose
NPM package in the application.
Make sure you have the connection string handy from the last section.
It should look similar to this:
mongodb+srv://username:passwo[email protected]/?retryWrites=true&w=majority
Here is a quick explanation for each item in the string:
mongodb://
: a required prefix to identify that this is a string in the standard connection format.username:password
: authentication credentials.cluster0.ndoexmd.mongodb.net
: the host where the database instance is running./defaultauthdb
: the authentication database to use if the connection string includes username:password@ authentication credentials. This is an optional item.?<options>
: a query string that specifies connection specific options as <name>=<value>
pairs. See Connection String Options for a full description of these options. This is an optional item.Re-open the /api/index.js
file in your code editor and update its contents to look like the following:
const express = require('express');
const dotenv = require('dotenv');
// New code
const mongoose = require("mongoose")
// Load env variables
dotenv.config({ path: './config/config.env' });
const app = express();
// New code
const mongoString = "mongodb+srv://username:[email protected]/?retryWrites=true&w=majority"
mongoose.connect(mongoString, () => {
console.log("Connected to MongoDB");
});
mongoose.connection.on("error", function(error) {
if (process.env.NODE_ENV === "development") {
console.log(error)
}
})
const PORT = process.env.PORT || 3000;
app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`));
To use the mongoose
NPM package in our code, we need to first require mongoose
at the top.
The mongoString
variable stores the connection string to your MongoDB database. Make sure you use the connection string and username/password provided to you on the Atlas website.
Using that connection string, we connect to the MongoDB database using the mongoose.connect() method.
Then, we added some code to listen for both any errors to occur or the successful connection to the database. We use the mongoose.on() method to listen for those events.
If an error occurs after the initial connection is made, we want to console.log()
the error so we understand what happened.
// New code
const mongoString = "mongodb+srv://username:[email protected]/?retryWrites=true&w=majority"
mongoose.connect(mongoString, () => {
console.log("Connected to MongoDB");
});
mongoose.connection.on("error", function(error) {
if (process.env.NODE_ENV === "development") {
console.log(error)
}
})
Save the /api/index.js
file and start the application again in your terminal (will automatically reload if it was already running with Nodemon):
npm run dev
You may see this warning:
To fix it, follow the instructions provided in the warning by adding this line:
mongoose.set("strictQuery", false);
Our code will look like the following:
const express = require('express');
const dotenv = require('dotenv');
const mongoose = require("mongoose")
// Load env variables
dotenv.config({ path: './config/config.env' });
const app = express();
const mongoString = "mongodb+srv://username:[email protected]/?retryWrites=true&w=majority"
// New code
mongoose.set('strictQuery', false);
mongoose.connect(mongoString, () => {
console.log("Connected to MongoDB");
});
mongoose.connection.on("error", function(error) {
if (process.env.NODE_ENV === "development") {
console.log(error)
}
})
const PORT = process.env.PORT || 3000;
app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`));
Save the index.js file and start the application again. If everything went as planned, you should see two output messages in the terminal:
Once you have everything connected and working, we can move on to the next step!