A step-by-step guide: How to use MongoDB with Node.js.
Tags: node, mongodb, database, javascript
Published: 2022-08-26 20:08:47


## Introduction

When working with a server, one will always have to save and retrieve data using a database. There are many server-side languages and databases available. In this article, you will learn how to use MongoDB with Node.js. 

MongoDB is a non-relational database. It is a document-oriented storage system. It stores and retrieves data in JSON format, instead of the traditional table and row format used in relational databases ( MYSQL, PostgreSQL ). 

### Prerequisites

1. A supported version of Node.js installed
2. A MongoDB Atlas [account](https://www.mongodb.com/atlas/database)
3. Basic knowledge of Node.js and Express.js


### Getting started
To demonstrate how to use [MongoDB](https://www.mongodb.com/) with [Node.js](https://nodejs.org/en), we will build a simple book inventory. You will learn how to add, get, edit, and remove books from your inventory. 


Make sure that your code editor has the following folders and files ready.

![vs.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1649135058297/-__VoKMs_.png)


### Installing dependencies

Quick note:
> [Mongoose](https://mongoosejs.com/) is a library that creates a connection between MongoDB and an Express-based application.

> [Dotenv](https://www.dotenv.org/) is used to load data from a `.env` file into a Node.js environment so it can access it using `process.env`.

Moving on, run the commands below in your terminal to install the dependencies needed for this project.

```
npm install express 
npm install mongoose
npm install  dotenv
```


### Retrieving the MongoDB connection string

 Login into your MongoDB Atlas [account](https://account.mongodb.com/account/login) to connect to the database from your Node.js application  

Follow these easy steps to retrieve the connection string:
- Click on `connect` on your Database Deployment dashboard.

![new_connect.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1649017678545/iXkA8S1Ap.png)

- Choose the `Connect to your application` option.

![connection.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1649180440535/Hu5xCifnD.png)

- Copy the connection string

![cluster.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1649180590922/H0ztpnMWw.png)

### Writing code

At this point, the dependencies and connection string should be ready for use. 

The `server.js` file should look like this for the time being 

```
const express = require('express')
const dotenv = require('dotenv')
const path = require('path')
const app = express()

dotenv.config({path: './config/config.env'})
app.use(express.json())

const port = process.env.port
app.listen(port, () => {
    console.log(`port ${port} connected...`)
})
```

The `config.env` file will hold the following environment variables:

```
port = 8080
mongo_uri = mongodb+srv://mongodb-template:<password>@cluster0.8lmmv.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
```
Restart your server after copying the code snippet above into your `config.env` file

 > Replace `<password>` with the actual password of the database


Next step, let's create a MongoDB connection, in the `db.js` file.
```
const mongoose = require('mongoose')

const connectDb = async () => {
const conn = await mongoose.connect(process.env.mongo_uri,  {
useNewUrlParser: true,
useUnifiedTopology: true
})
console.log(`mongodb connected: ${conn.connection.host}`)
}

module.exports = connectDb

```


Now that the database connection is ready, update the `server.js` file. 

```
const express = require('express')
const dotenv = require('dotenv')
const connectDb = require('./database/db')
const app = express()

dotenv.config({path:'./config/config.env'})
app.use(express.json())

//database connection
connectDb()

const port = process.env.port
app.listen(port, () => {
    console.log(`port ${port} connected...`)
})

```


### Creating the schema 

MongoDB schema is a JSON object that decides what the database is allowed to be stored.

Setting up `BookSchema.js` :
```
const mongoose = require('mongoose')

const BookSchema = new mongoose.Schema({
    title:{
        type:String,
        required:true,
        unique:true
    },
    author:{
        type:String,
        required:true,
        unique:true
    },
    isbn:{
        type:String,
        unique:true
    }
})

module.exports = mongoose.model('BookSchema', BookSchema)

```

### Routes

Starting on the `book.js` file, bring in the `router` and `BookSchema` model.

```
const router = require('express').Router()
const Book = require('../model/BookSchema')
```


The `book.js` file will contain the following requests:


##### POST request

```
router.post('/', async (req,res) => {
    const { title, author, isbn } = req.body
    const newBook = await Book.create({ title, author, isbn })
    res.status(201).json({ 
        success:true, 
        data:newBook 
    })
})
```
The code snippet above will store the `name, author, and isbn` of a book.


##### GET request


> There will be two variants of the `GET` request. One will `GET` all books while the other will `GET` just a particular book.


```
router.get('/',  async (req,res) => {
    const books = await Book.find()
    res.status(200).json({ 
        success:true, 
        data: books, 
        num: books.length
    })
})

router.get('/:id',  async (req,res) => {
  const book = await Book.findById(req.params.id)  
  res.status(200).json({ 
      success:true, 
      data: book 
    })
})
```



##### PUT request

```
router.put('/:id', async (req,res) => {
    let book = await Book.findById(req.params.id)
    book = await Book.findByIdAndUpdate(req.params.id, {$set:req.body}, {
        new:true,
        runValidator:false
    })  
    res.status(200).json({ 
        success:true, 
        data: book 
    })
})
```
The code snippet above updates the book details that match the specified ID.


#####  DELETE request
> This operation will also have two variants in case we want to DELETE one or all entries from the database.


```
router.delete('/:id', async (req,res) => {
    await Book.findByIdAndRemove(req.params.id)
    res.status(200).json({ 
        success:true, 
        data: 'book deleted' 
    })
})

router.delete('/', async (req,res) => {
    await Book.deleteMany()
   res.status(200).json({ 
       success:true, 
       data: 'All books deleted' 
    })
})
```




Lastly, export the router. 

```
module.exports = router
```

Take a deep breath. At this point, we are almost done.

Update the `server.js` file one last time with the `router`.

```
const express = require('express')
const dotenv = require('dotenv')
const connectDb = require('./database/db')
const app = express()

dotenv.config({path:'./config/config.env'})
app.use(express.json())

//database connection
connectDb()

//mount the route
const bookRoute = require('./routes/book')
app.use('/api/v1/book', bookRoute)

const port = process.env.port
app.listen(port, () => {
    console.log(`port ${port} connected...`)
})
```

### Conclusion
In this article, you learned how to use MongoDB with Node.js by creating a simple project. I hope you found this tutorial easy to follow. 

Happy coding! 😀

### Credits
-  [MongoDB docs](https://www.mongodb.com/docs/)
- [Project GitHub Link](https://github.com/backendbro/mongodb_template)