Connect MongoDB with Node.js

mongoDB wallpaper

In this new post, I show how to connect our application to MongoDB using Node.js. Let’s start with the installation of MongoDB if you want to test your application locally.

The source code of this post is available on GitHub.

Install MongoDB

First, if we want to play locally on our laptop, we have to install MongoDB. Download the installer from this link and follow the instructions. After you run the UI, you should see a similar screenshot.

Local MongoDB - Connect MongoDB with Node.js
Local MongoDB

MongoDB on line

There is another option: use MongoDB online. To do so, you have to create a free account on the MongoDB website. You should see the following screenshot.

MongoDB website - Connect MongoDB with Node.js
MongoDB website

Now, the first activity we have to do to use MongoDB online is to create an organization.

MongoDB requires to create an organization
MongoDB requires to create an organization

The next screen is asking for a selection of the type of the database we want to use. My choice is to select MongoDB Atlas.

Create an organization in MongoDB
Create an organization in MongoDB

Then, click Next. On the next screen, we can add more members and other basic settings. At the moment, nothing is required.

Create organization - Second screen
Create organization – Second screen

Now, click Create Organization. At the end, you are redirected to the Project page.

Projects page in MongoDB
Projects page in MongoDB

Create a new project

So, clicking on the button New Project, we are redirected to the Create a Project page.

Create a new project
Create a new project

Here, we can insert the Name of Your Project. Also, it is possible to add tags that help you to identify and categorize your project.

Create new project - Screen 2
Create a new project – Screen 2

Now, on the second screen, we can add more users that can access the database. Click on the button Create Project. After this action is complete, we can see the Project Settings.

Project setting page
Project setting page

Create a cluster

The next step to have a usable MongoDB database is to create a cluster. A free cluster provides a small-scale development environment to host your data. Free clusters never expire, and provide access to a subset of Atlas features and functionality.

Create a cluster
Create a cluster

So, now we have to click on the Create button. In the next screen, we have to choose a few settings for the cluster. The name of the cluster is not changeable. The type of service I choose is M0 because it is free and it is perfect for my tests.

Deploy your cluster with MongoDB
Deploy your cluster with MongoDB

Then, I have to choose the Provider and my choice is Azure. Then, I have to select the Region and I choose Ireland because it is close to where I live. Then, click on Create Deployment.

Connect to the cluster
Connect to the cluster

Now, I can see that the cluster is created and my IP is added to the access list. Plus, an account is been created for me to access the cluster. This form offers you a Username and a Password. You can change those and then click on the button Create Database User.

Cluster created
Cluster created

So that, the cluster is created and I am ready to Choose a connection method. Because I want to connect my Node.js project to the MongoDB, I choose the first option Drivers.

Choose the connection type
Choose the connection type

Then, I have the instructions on how to install the driver for Node.js and what the connection string is. The next step is to create a simple project in Node.js to connect to the database.

Connection settings
Connection settings

Create a project with Node.js

In my previous post called Introduction to Node.js, I showed how to start a project with Node.js. So, I have to install a package for my project called mongoose that helps with the connection to the MongoDB database. In the Terminal, type and execute this command

npm install mongoose

Now, in the app.js, I require to use this package in my project adding at the top this line

const mongoose = require('mongoose')

So, I want to connect my project to the database using the variable mongoose. For that, I can use the function connect and pass the connection string that I can copy from the screen above. Now, the following code open the connection and write a text in the console

mongoose.connect('<your connection string>')
    .then(() => {
        console.log('Connected with MongoDB')
    })
    .catch((err) => {
        console.error('Error connection to MongoDB', err)
    })

Run the application and check that the connection is up and running.

Where is the database name?

If you use the connection string from the screen above, for example

mongodb+srv://erossi03:pw2@cluster0.j09uw.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0

when I run the application, MongoDB creates a new collection called test. Probably, this is not what I want. If I want the add the name of the collection, add the name before the ?, for example

mongodb+srv://erossi03:pw2@cluster0.j09uw.mongodb.net/MyDatabase?retryWrites=true&w=majority&appName=Cluster0

Create a User model

We have to tell MongoDB what kind of data we want to save. Like other languages, I have to define in the code a model for the data. Thing a model in NoSQL databases like MongoDB as a schema of the table in a relational database. So, my first model will be to save the base data for a user.

So, in the root of the project, create a model folder that conventionally has all the schema. Then, create a file called user.js where I define the structure. As a convention, the name of the schema is the name of the content using the singular word (for example user not users). The collection will be plural, for example users. This a collection as a table in a relational database.

const mongoose = require('mongoose')

const userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        min: 3,
        max: 256
    },
    email: {
        type: String,
        required: true,
        min: 3,
        max: 256
    },
    password: {
        type: String,
        required: true,
        min: 6,
        max: 256
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
})

module.exports = mongoose.model('User', userSchema);

In this code, mongoose is required because is the package that helps with the connection with the database but also with the definition of the schema and work on the collections.

To define the schema, I use the function Schema that needs as a parameter the structure of the collection. Each “field” is define straight in the structure and then in the {} there is the definition of the table.

The types we can use are define from the SchemaTypes available with examples on the official documentation and they are

For example, the “field” username is a required String with minimum 3 characters and maximum 156. After defining all the fields, we have to export the schema using

module.exports = mongoose.model('User', userSchema);

Add User route

Now, I have to create a route for Users using the model I created above. I create a new folder called routes where I will add all the routes from my application. Now, I create a new file users.js. In this file I’m going to define a new router, add the model and export the router.

const express = require('express')
const router = express.Router();

const User = require('../models/user')

module.exports = router;

This code is enough to create the collection in MongoDB. If you look at your cluster or local instance, you can see your new database

The database is created in MongoDB

Add the register path

As you can see in the code above, I added a new post function to register a new user. That means I can consume the path /api/users/register to register a new user using a POST HTTP verbs. Also, I have to pass as a payload email, username and password as a json. An example of that is here

{
  "email": "erossi03@student.birkbeck.ac.uk",
  "username": "test",
  "password": "Test!2024"
}

In order to read the body of the request, I have to use another package called body-parser. I have to add this package only in the main file of the application, usually app.js. This package gives us the ability to read the body of the request and parse the request. See the following code

const express = require('express')
const router = express.Router();

const User = require('../models/user')

router.post('/register', async (req, res) => {
    // prepare the data to save in the database
    const user = new User({
        username: req.body.username,
        email: req.body.email,
        password: req.body.password
    });

    // save the user in the database and return the saved user
    const savedUser = await user.save();
    res.send(savedUser);
})

module.exports = router;

req.body.username is what the package is doing. Basically, the req contains in the body the json passed in the POST request. Now, I can tell to search the tag username in this json using the package.

If I fast forward to the result, you can see in the following screenshot how I call the function and get the result. I’m using Thunder Client or Postman to send the requests for test because it is integrated in Visual Studio Code.

Using Thunder Client to test the application
Using Thunder Client to test the application

Then, to save the user in the collection, I use the function save and then return using the response res the full json of the new user.

Add the route on the app

The past part is to add the route and other packages (like body-parser) to our application. So, I replace the app.js content with the following

// add packages dependencies
const express = require('express')
const mongoose = require('mongoose')

// Importing the body-parser to parse the json
const bodyParser = require('body-parser');

// importing routes (middleware)
const userRoute = require('./routes/users')

// define the application
const app = express()

// add body-parser to the app
app.use(bodyParser.json());

// add routes
app.use('/api/users', userRoute);

// open the connection with the database
mongoose.connect('mongodb+srv://erossi03:pw2@cluster0.j09uw.mongodb.net/PiazzaDatabase?retryWrites=true&w=majority&appName=Cluster0')
    .then(() => {
        console.log('Connected with MongoDB')
    })
    .catch((err) => {
        console.error('Error connection to MongoDB', err)
    });

app.listen(3000, () => {
    console.log('The application Piazza is up and running')
});

Now, it is time to run and application and play with it. Try to send a request using one of suggested tool and doing your tests.

Wrap up

I hope this post can help you to start working with MongoDB in your Node.js project. Let me know if you need more clarification.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.