MongoDB

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
- Signup on ‣Log in | MongoDB
- Create a
fr
ee M0
cluster
- Create a
User
- Install MongoDB compass
Put the connection URL to connect to the database
open downloaded MongoDB application.
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
- Paste password at selected place. (From onwards we going to everything in application)
- 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
Create a new
Database
calledtodo-app
Create two collections inside it
users
todos
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:
Create: Adding new documents to a collection.
Read: Retrieving documents from a collection.
Update: Modifying existing documents in a collection.
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.
- Initialise a new Node.js project
npm init -y
- Install dependencies
npm install express mongoose
Create the skeleton for 4 routes - index.js
POST /signup
POST /login
POST /todo (authenticated)
GET /todos (authenticated)
- 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);
- 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
};
- 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
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.
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.
todo endpoint:
Method: post
Url: http://localhost:3000/todo
Body:
{ "title":"go to gym" }
todos endpoint:
Method: GET
url: http://localhost:3000/todos
click on send
check MongoDB database.
Subscribe to my newsletter
Read articles from Neha Sawant directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
