MongoDB

Neha SawantNeha Sawant
5 min read

What are databases

Databases are organized collections of data that are structured to enable efficient storage, retrieval, and management of information.

Whenever you create a full stack app , you persist data in databases

Types of databases

  • Relational Databases: Use tables to store data and relationships between data (e.g., MySQL, PostgreSQL).

  • NoSQL Databases: Designed for more flexible data models and often used for big data or real-time web applications (e.g., MongoDB).

  • Graph Databases: Store data in nodes and edges to represent relationships (e.g., Neo4j).

  • Vector Databases: Used in ML to store data in the form of embeddings

MongoDB and NoSQL databases

NoSQL databases are a broad category of database systems that diverge from the traditional relational model used in SQL databases.

They are designed to handle a variety of data models and workloads that may not fit neatly into the tabular schema of relational databases.

Properties

  • Schema Flexibility: NoSQL databases often allow for a flexible schema, meaning you can store data in formats that don't require a fixed structure.

  • Scalability: Many NoSQL databases are designed to scale out horizontally, making it easier to distribute data across multiple servers and handle large volumes of traffic.

MongoDB

MongoDB is a NoSQL database that uses a document-oriented approach. Data is stored in flexible, JSON-like documents, which can have nested structures and varied fields.

  • MongoDB stores data as JSON-like documents (BSON), which is perfect for JavaScript-based apps.

  • Designed for horizontal scaling (across many servers).

Creating a free MongoDB Server

  1. Signup on ‣Log in | MongoDB

  1. Create a free M0 cluster

  1. Create a User

  1. Install MongoDB compass

  1. Put the connection URL to connect to the database

  2. open downloaded MongoDB application.

  3. copy link and paste to application.

url: mongodb+srv://nehasawant719:NeK8R4OEuxbRM68u@cluster0.vyc3yj0.mongodb.net/

pwd: for password go to web mongodb website→ database access → edit → generate password copy pwd

  1. Paste password at selected place. (From onwards we going to everything in application)

  1. Connect it. and create database eg. todo-app-database and create collections - users, todos.

Connection string:

Seeding data in the DB:

Lets put some data in the Cluster manually

  1. Create a new Database called todo-app

  2. Create two collections inside it

    1. users

    2. todos

  3. Seed some data inside the collections

Users table

TODO table:

CRUD Operations

CRUD operations in MongoDB refer to the basic operations you can perform on documents within a MongoDB database. CRUD stands for:

  1. Create: Adding new documents to a collection.

  2. Read: Retrieving documents from a collection.

  3. Update: Modifying existing documents in a collection.

  4. Delete: Removing documents from a collection.

Creating the backend of a todo app:

Lets now create a todo application with the data being persisted in the database.

  1. Initialise a new Node.js project

npm init -y

  1. Install dependencies

npm install express mongoose

  1. Create the skeleton for 4 routes - index.js

    • POST /signup

    • POST /login

    • POST /todo (authenticated)

    • GET /todos (authenticated)

  1. Implement code in index.js
const express = require("express");
const { UserModel, TodoModel} = require("./db");
const { auth, JWT_SECRET} = require ("./auth");
const jwt = require("jsonwebtoken");
const mongoose = require("mongoose");


mongoose.connect("mongodb+srv://nehasawant719:NeK8R4OEuxbRM68u@cluster0.vyc3yj0.mongodb.net/todo-neha");
const app = express();
app.use(express.json()) // to parse body -> req.body.email


app.post("/signup",async function(req,res){
    const email = req.body.email;
    const password = req.body.password;
    const name = req.body.name;

    await UserModel.create({
        email: email,
        password: password,
        name: name
    });

    res.json({
        message: "You are logged in"
    })
});


app.post("/signin", async function(req,res){

    const email = req.body.email;
    const password = req.body.password;

    const user = await UserModel.findOne({
        email: email,
        password: password,
    });

    console.log(user);

    if (user) {
        const token = jwt.sign({
            id: user._id.toString()
        }, JWT_SECRET);

        res.json({
            token: token
        })
    } else {
        res.status(403).json({
            message: "Incorrect creds"
        })
    }
});



app.post("/todo", auth, async function(req,res){
const userId = req.userId;
    const title = req.body.title;
    const done = req.body.done;

    await TodoModel.create({
        userId,
        title,
        done
    });

    res.json({
        userId: userId
    })
});


app.post("/todos", auth, async function(req,res){
    const userId = req.userId;

    const todos = await TodoModel.find({
        userId
    });

    res.json({
        todos
    })
});


app.listen(3000);
  1. Implement code in auth.js
const jwt = require("jsonwebtoken");

const JWT_SECRET = "11111111";

function auth(req, res, next) {
    const token = req.headers.token;
    try {
        const response = jwt.verify(token, JWT_SECRET);
        req.userId = response.id;
        next();
    } catch (err) {
        return res.status(403).json({ message: "Invalid token" });
    }
}

module.exports = {
    auth,
    JWT_SECRET
};
  1. Implement code in db.js
const mongoose = require('mongoose');
const Schema =mongoose.Schema;
const ObjectId = mongoose.ObjectId;

const User = new Schema({
    email: String,
    password: String,
    name: String
});

const Todo = new Schema({
    title: String,
    done: Boolean,
    userId: ObjectId
});

const UserModel = mongoose.model('User', User);
const TodoModel = mongoose.model('Todo', Todo);

module.exports = {
    UserModel,
    TodoModel
}

Testing your app:

Try testing your app in Postman next

  1. signup endpoint:
  • Method: post

  • Url: http://localhost:3000/signup

  • body:

{
    "username":"neha@gmail.com",
    "password":"123123",
    "name":"neha"
}

click on send.

you will see that signup data is added in mongodb instace.

  1. Signin endpoint:
  • Method: post

  • Url: http://localhost:3000/signin

  • body:

      {
          "username":"neha@gmail.com",
          "password":"123123"
      }
    

    click on send. You will get token. copy that token and enter at headers section in signin endpoint only.

  1. todo endpoint:
  • Method: post

  • Url: http://localhost:3000/todo

  • Body:

    •         {
                "title":"go to gym"
              }
      

  1. todos endpoint:

Method: GET

url: http://localhost:3000/todos

click on send

  1. check MongoDB database.

0
Subscribe to my newsletter

Read articles from Neha Sawant directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Neha Sawant
Neha Sawant