0% found this document useful (0 votes)
6 views8 pages

Install MongoDB on macOS Guide

Uploaded by

hemalatha.s
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views8 pages

Install MongoDB on macOS Guide

Uploaded by

hemalatha.s
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1) Install a NoSQL database of your choice (such as MongoDB, Cassandra, Redis,

Neo4j, c.) on your local machine.

Install MangoDB (For Mac)


Open terminal and follow the commands
brew tap mongodb/brew
brew install mongodb-community
brew services start mongodb-community
mongod --version

Step 1: Extract the Archive

1. Go to Downloads in Finder.
2. Double-click [Link] (or .tar).
→ It should create a folder like mongodb-macos-arm64-8.0.13.

Step 2: Move MongoDB to /usr/local/

Open your Terminal and run:

sudo mkdir -p /usr/local/mongodb

sudo mv ~/Downloads/mongodb-macos-arm64-8.0.13/ /usr/local/mongodb

Step 3: Add MongoDB to Your PATH

Edit your shell config file (.zshrc since you’re on macOS with zsh):

nano ~/.zshrc

export PATH="/usr/local/mongodb/mongodb-macos-arm64-8.0.13/bin:$PATH"

Save & exit (Ctrl+O, Enter, Ctrl+X).

source ~/.zshrc

Step 4: Create Data Directory

MongoDB needs a folder to store data:


sudo mkdir -p /usr/local/var/mongodb

sudo mkdir -p /usr/local/var/log/mongodb

sudo chown -R $(whoami) /usr/local/var/mongodb

sudo chown -R $(whoami) /usr/local/var/log/mongodb

Step 5: Start MongoDB

mongod --dbpath /usr/local/var/mongodb

Step 6: Open Another Terminal for the Shell

Mongosh

Step 7: Connect from VS Code

Now go back to VS Code → MongoDB extension → Click Connect → Enter:

mongodb://localhost:27017
2) Practice creating, reading, updating, and deleting data in your chosen
NoSQL database. Get comfortable with the syntax and APIs provided by the
database.

Step 1: Open VS Code and Create Project Folder

1. Open VS Code.
2. Open a new terminal (Ctrl + ` or View → Terminal).

Run these commands to make the root project folder and go inside it:
mkdir student-crud-

node cd student-crud-

node code .

INSIDE THE STUDENT_CRUD_NODE

npm init -y

This will create the [Link] file.

In VS Code file explorer:

1. Right-click → New File → name it .env.

Paste this inside:


MONGO_URI=mongodb://[Link]:27017

DB_NAME=student_crud

2. PORT=3000

Install Dependencies

In VS Code terminal:

npm install mongodb dotenv


FILE STRUCTURE

Crud_server.js
import { createServer } from "http";
import { MongoClient, ObjectId } from "mongodb";
import { readFile } from "fs/promises";
import { extname } from
"path"; import "dotenv/config";
const client = new MongoClient([Link].MONGO_URI);
const db = [Link]([Link].DB_NAME);
const students = [Link]("students");
const mimeTypes = {
".html": "text/html",
".css": "text/css",
".js":
"application/javascript",
".json": "application/json",
};
async function serveFile(path) {
try {
const data = await readFile(path);
const type = mimeTypes[extname(path)] || "text/plain";
return { status: 200, data, type };
} catch {
return { status: 404, data: "Not Found", type: "text/plain" };
}
}
const server = createServer(async (req, res) => {
if ([Link]("/api/students")) {
// API routes
if ([Link] === "GET") {
const all = await [Link]().toArray();
[Link](200, { "Content-Type": "application/json" });
[Link]([Link](all));
}
else if ([Link] === "POST")
{ let body = "";
[Link]("data", (chunk) => (body += chunk));
[Link]("end", async () => {
const doc = [Link](body);
const result = await [Link](doc);
[Link](201, { "Content-Type": "application/json" });
[Link]([Link]({ _id: [Link], ...doc }));
});
}
else if ([Link] === "PUT") {
const id =
[Link]("/").pop(); let body
= "";
[Link]("data", (chunk) => (body += chunk));
[Link]("end", async () => {
const update = [Link](body);
await [Link](
{ _id: new ObjectId(id) },
{ $set: update }
);
[Link](200, { "Content-Type": "application/json" });
[Link]([Link]({ ok: true }));
});
}
else if ([Link] === "DELETE")
{ const id = [Link]("/").pop();
await [Link]({ _id: new ObjectId(id) });
[Link](200, { "Content-Type": "application/json" });
[Link]([Link]({ ok: true }));
}
} else {
// Serve static files
const filePath =
[Link] === "/" ? "public/[Link]" : `public${[Link]}`;
const { status, data, type } = await serveFile(filePath);
[Link](status, { "Content-Type": type });
[Link](data);
}
});
[Link]([Link], async () => {
await [Link]();
[Link](`✅ Server running at [Link]
});
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Student Management</title>
<link rel="stylesheet" href="[Link]"/>
</head>
<body>
<div class="container">
<h1>Student Management</h1>
<form id="studentForm">
<input type="text" id="name" placeholder="Name" required />
<input type="number" id="age" placeholder="Age" required />
<input type="text" id="course" placeholder="Course" required />
<input type="text" id="grade" placeholder="Grade" required />
<button type="submit">Add Student</button>
</form>
<h2>Students</h2>
<ul id="studentList"></ul>
</div>
<script>
async function loadStudents() {
const res = await fetch('/api/students');
const data = await [Link]();
const list = [Link]('studentList');
[Link] = '';
[Link](s => {
const li = [Link]('li');
[Link] = `
${[Link]} (${[Link]}) - Age: ${[Link]}, Grade: <b>${[Link]}</b>
`;
// Delete button
const delBtn = [Link]('button');
[Link] = "❌";
[Link] = async () => {
await fetch('/api/students/' + s._id, { method: 'DELETE' });
loadStudents();
};
// Update button
const updBtn = [Link]('button');
[Link] = "✏ Update Grade";
[Link] = () => {
const newGrade = prompt("Enter new grade:", [Link]);
if (newGrade) {
fetch('/api/students/' + s._id,
{ method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: [Link]({ grade: newGrade })
}).then(loadStudents);
}
};
[Link](updBtn);
[Link](delBtn);
[Link](li);
});
}
[Link]('studentForm').addEventListener('submit', async (e) => {
[Link]();
const student = {
name: [Link]('name').value,
age:
parseInt([Link]('age').value),
course: [Link]('course').value,
grade: [Link]('grade').value,
};
await fetch('/api/students',
{ method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: [Link](student)
});
[Link]();
loadStudents();
});
loadStudents();
</script>
</body>
</html>
[Link]
body {
font-family: Arial, sans-
serif; background: #f4f4f9;
margin: 0;
padding: 0;
}
.container
{ width:
500px;
margin: 40px auto;
padding: 20px;
background: #fff;
border-radius:
10px;
box-shadow: 0 2px 6px rgba(0,0,0,0.2);
}
h1, h2 {
text-align: center;
}
form
{ display:
flex;
flex-direction:
column; gap: 10px;
}
form input, form button {
padding: 10px;
font-size: 16px;
}
#studentList
{ list-style:
none; padding:
0;
}
#studentList li
{ background:
#e8f0fe; margin: 5px
0; padding: 10px;
border-radius: 6px;
display: flex;
justify-content: space-
between; align-items: center;
}
[Link]
{
"name": "student-crud-
node", "version": "1.0.0",
"description": "",
"main":
"[Link]",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "module",
"dependencies":
{ "dotenv": "^17.2.2",
"mongodb": "^6.19.0"
}
}
OUTPUT:

You might also like