Databases and CRUD operations in MongoDB using Mongoose

Databases and CRUD operations in MongoDB using Mongoose

Introduction

Hello everyone, Im Hasnain. In this article, we'll learn about Databases and their Types, MongoDB, Mongoose and CRUD operations with Mongoose

Before we understand how to perform CRUD(Create, Read, Update, Delete) operations in the MongoDB database with Mongoose, let's have a look at what are databases.

What are Databases?

  • Databases are used for storing, maintaining and accessing any sort of data.

  • We can collect any information and gather it in one place to analyze and perform operations.

Types of Databases

There are many types of databases but most databases can be categorized as either relational or non-relational. The main difference between them is how they store their information.

Relational Databases

A relational database stores information in the form of 'Tables' that contain specific pieces of data and their types structured in rows and columns.

Relational databases use Structured Query Language(SQL).

For Example.

Customer IDNameAddress
C0001JohnD-142, Example address
C0002TysonB-4, Example address

Non - Relational Database

Non-relational databases a.k.a NoSQL databases are different from Relational Databases. Non-relational databases use a storage model that is optimized for the specific requirements of the type of data being stored. For example, data may be stored as simple key/value pairs, as JSON documents, or as a graph consisting of edges and vertices.

Non-relational databases are faster because a query doesn't have to search in several tables to find the answer.

Query: A query can either be a request for data results from your database or action on the data, or both.

Non-relational databases are best for storing large quantities of complex data that may be changed frequently and for handling different types of data.

Example

{
    "id": 4,
    "name": "The Park Camper",
    "duration": 10,
    "maxGroupSize": 15,
    "difficulty": "medium",
    "ratingsAverage": 4.9,
    "ratingsQuantity": 19,
    "price": 1497,
    "summary": "Breathing in Nature in America's most spectacular National Parks",
    "description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum!",
    "imageCover": "tour-5-cover.jpg",
    "images": ["tour-5-1.jpg", "tour-5-2.jpg", "tour-5-3.jpg"],
    "startDates": ["2021-08-05,10:00", "2022-03-20,10:00", "2022-08-12,10:00"]
  }

What is MongoDB?

MongoDB is a NoSQL database used for high-volume data storage. In Mongo, each database can contain one or more collections. You can think of these collections as 'Tables' in a traditional relational database.

Each collection can contain one or more data structures called 'Documents'. You can think of these Documents as 'Rows' in a relational database.

Features of MongoDB

  • Document Based: MongoDB stores data in documents (field-value pair data structures, NoSQL)

  • Scalable: Very easy to distribute data across multiple machines as your users and amount of data grows

  • Flexible: No document data schema is required, so each document can have a different number and type of fields.

  • Free and Open Source

What is Mongoose?

Mongoose is an Object Data Modelling (ODM) library for MongoDB & NodeJS. a higher level of abstraction.

ODM: Object Data Modelling library is just a way to write JavaScript Code that will then interact with the database

We can just use a regular MongoDB driver to access our database but Mongoose gives us a lot more functionality, allowing us to faster and simpler development of our application

Features of Mongoose

  • Schemas to model data and relationships

  • Easy data validation

  • Simple Query API

  • Middleware

Mongoose Schema

In Mongoose, a Schema is where we model our data, by describing the structure of the data, default values and validation.

Mongoose Model

A model is a wrapper for the schema. providing an interface to the database for CRUD operations.

Connecting our Database with the Express app

Now that you have learned about databases, MongoDB and Mongoose, let's connect our NodeJS, Express application with MongoDB and perform CRUD operations with Mongoose.

  • Go to MongoDB Atlas

  • Click on Connect to your Cluster

  • Click on 'Connect your application'

  • Make sure you select NodeJS and copy the Connection String.

  • Now, Inside your application, we'll create it as an environment variable in our config file

  • create a variable DATABASE and paste the connection string

  • In the connection string, you'll have <password>. replace it with your database password and replace /test in your connection string with your database name

Installing Mongoose

 $ npm install mongoose
  • Importing
//Import using NodeJs 'require()'
const mongoose = require('mongoose')
// Using ES6 imports
import mongoose from 'mongoose';

Router

router
  .route('/')
  .get(docController.getAllDoc)
  .post(docController.createDoc);
router
  .route('/:id')
  .get(docController.getDoc)
  .patch(docController.updateDoc)
  .delete(docController.deleteDoc);

Creating Documents

exports.createDoc = async (req, res) => {
  try {
    const newDoc = await Doc.create(req.body);
    console.log(req.body);
    res.status(201).json({
      status: 'success',
      data: {
        Doc: newDoc
      }
    });
  } catch (err) {
    res.status(400).json({
      status: 'fail',
      message: err
    });
  }
};

Output

  • Send POST request

Reading Documents

exports.getAllDoc = async (req, res) => {
  try {
    const doc = await Doc.find(); 



    //Send response
    res.status(200).json({
      status: 'success',
      results: doc.length,
      data: {
        doc
      }
    });
  } catch (err) {
    res.status(404).json({
      status: 'fail',
      message: err
    });
  }
};

Output

  • Send GET request

Updating Documents

exports.updateDoc = async (req, res) => {
  try {
    const doc = await Tour.findByIdAndUpdate(req.params.id, req.body, {
      new: true
    });
    res.status(200).json({
      status: 'success',
      data: {
        doc
      }
    });
  } catch (err) {
    res.status(400).json({
      status: 'fail',
      message: 'Invalid data sent!'
    });
  }
};

Output

  • Send PATCH request

Deleting Documents

exports.deleteDoc = async (req, res) => {
  try {
    await Doc.findByIdAndDelete(req.params.id);
    res.status(204).json({
      status: 'success',
      data: null
    });
  } catch (err) {
    res.status(400).json({
      status: 'fail',
      message: 'Invalid data sent!'
    });
  }
};

Output

  • Send DELETE request

  • Delete request doesn't show any content but it deletes if you select your document by ID as I did

The End

That's it for this article, I hope you like it and you learned something new today. If you have any queries, post them in the comments. Thanks for reading and I'll see you in the next one.