DEV Community

Cover image for A step-by-step guide: How to use MongoDB with Node.js.
Ukagha Nzubechukwu
Ukagha Nzubechukwu

Posted on • Updated on

A step-by-step guide: How to use MongoDB with Node.js.

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
  3. Basic knowledge of Node.js and Express.js

Getting started

To demonstrate how to use MongoDB with Node.js, 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

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 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
Enter fullscreen mode Exit fullscreen mode

Retrieving the MongoDB connection string

Login into your MongoDB Atlas account 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

  • Choose the Connect to your application option.

connection.png

  • Copy the connection string

cluster.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...`)
})
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

Routes

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

const router = require('express').Router()
const Book = require('../model/BookSchema')
Enter fullscreen mode Exit fullscreen mode

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 
    })
})
Enter fullscreen mode Exit fullscreen mode

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 
    })
})
Enter fullscreen mode Exit fullscreen mode
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 
    })
})
Enter fullscreen mode Exit fullscreen mode

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' 
    })
})
Enter fullscreen mode Exit fullscreen mode

Lastly, export the router.

module.exports = router
Enter fullscreen mode Exit fullscreen mode

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...`)
})
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)