How to use MongoDB with Node.js

How to use MongoDB with Node.js

ยท

4 min read

Introduction

When building backend applications, we always have to save and retrieve data using a database. There are many server-side languages and databases. In this article, we 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 )

Goals

This article will focus on the following:

  • Get the MongoDB connection string

  • Build a simple book inventory

Prerequisites

  1. A supported version of Node.js installed

  2. A MongoDB Atlas account

  3. Basic knowledge of Node.js and Express.js

Getting started

Using MongoDB and Node.js, we will build a simple book inventory. We will learn how to add, get, edit and remove books from the list.

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

Installing dependencies

Quick note:

Mongoose is a library that creates a connection between MongoDB and an Express-based application.

Dotenv is used to load data from our config.env file into the environment so we 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 connection string.

  1. Click connect on your database deployment dashboard.

  2. Choose the Connect to your application option.

  3. Copy the connection string.

Let's delve in

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

server.js 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...`)
})

config.env will hold all environment variables.

port = 8080
mongo_uri = mongodb+srv://mongodb-template:<password>@cluster0.8lmmv.mongodb.net/myFirstDatabase?retryWrites=true&w=majority

Replace <password> with the actual password of the database

Restart your server after pasting the credentials above into the config.env file

Next step, let's create a MongoDB connection, in db.js.

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

The database connection is up and running, now update server.js

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 store.

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
}, 
isbn:{ 
type:String, 
unique:true 
} 
})

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

Routes

book.js should look like this in the meanwhile:

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


module.exports = router

book.js will be populated with the following requests:

POST request:

The code below will take in a title, author, and ISBN. Then proceed to store it in the database.

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 
    })
})

GET requests:

There will be two variants of the GET request. One will GET all books, while the other will get a particular book.

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

// get a particular book
router.get('/:id', async (req,res) => { 
    const book = await Book.findById(req.params.id)
    res.status(200).json({ success:true, data: book }) 
})
PUT requests: They are used to edit particular records in the database.
router.put('/:id', async (req,res) => { 
let book = await Book.findById(req.params.id) 
if(!book){
    return res.status(404).json({success:false, message:"No book found"})
    }
book = await Book.findByIdAndUpdate(req.params.id, 
{$set:req.body}, 
{ new:true, runValidator:false })

res.status(200).json({ success:true, data: book }) })
DELETE request:

There will also be two variants of the DELETE request. The first one will DELETE all entries, while the other will DELETE a particular entry.

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

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

Take a deep breath. At this point, we are almost done with our project. server.js should be updated with the router module.

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

So far, we've learned how to use MongoDB with Node.js by creating a simple project. I hope you found this tutorial easy to navigate.

Link to the entire project on GitHub. Happy coding ๐Ÿ˜€

Credits

ย