Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

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

Posted on • Edited 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 Atlasaccount
  3. Basic knowledge of Node.js and Express.js

Getting started

To demonstrate how to useMongoDB withNode.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 usingprocess.env.

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

npm install express npm install mongoosenpm install  dotenv
Enter fullscreen modeExit fullscreen mode

Retrieving the MongoDB connection string

Login into your MongoDB Atlasaccount to connect to the database from your Node.js application

Follow these easy steps to retrieve the connection string:

  • Click onconnect on your Database Deployment dashboard.

new_connect.png

  • Choose theConnect 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.

Theserver.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.portapp.listen(port, () => {    console.log(`port ${port} connected...`)})
Enter fullscreen modeExit fullscreen mode

Theconfig.env file will hold the following environment variables:

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

Restart your server after copying the code snippet above into yourconfig.env file

Replace<password> with the actual password of the database

Next step, let's create a MongoDB connection, in thedb.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 modeExit fullscreen mode

Now that the database connection is ready, update theserver.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 connectionconnectDb()const port = process.env.portapp.listen(port, () => {    console.log(`port ${port} connected...`)})
Enter fullscreen modeExit fullscreen mode

Creating the schema

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

Setting upBookSchema.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 modeExit fullscreen mode

Routes

Starting on thebook.js file, bring in therouter andBookSchema model.

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

Thebook.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 modeExit fullscreen mode

The code snippet above will store thename, author, and isbn of a book.

GET request

There will be two variants of theGET request. One willGET all books while the other willGET 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 modeExit 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 modeExit 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 modeExit fullscreen mode

Lastly, export the router.

module.exports = router
Enter fullscreen modeExit fullscreen mode

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

Update theserver.js file one last time with therouter.

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 connectionconnectDb()//mount the routeconst bookRoute = require('./routes/book')app.use('/api/v1/book', bookRoute)const port = process.env.portapp.listen(port, () => {    console.log(`port ${port} connected...`)})
Enter fullscreen modeExit 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Passionate about everything Javascript, Node.js, Typescript, Open Source, DS, and, System Design.
  • Education
    University of Benin
  • Joined

More fromUkagha Nzubechukwu

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp