ROHINI COLLEGE OFENGINEERING &
TECHNOLOGY
24CA206-FULL STACK WEB DEVELOPMENT
I YEAR-IISEM –COMPUTER APPLICATION
By,
Mrs. R.S.RAMYA DEVI
Adding and Retrieving Data in MongoDB with Node.js
•What is MongoDB?
A NoSQL database for storing JSON-like documents
•What is Node.js?
A JavaScript runtime for building backend applications
•Purpose of the Presentation
How to connect, insert, and retrieve data in MongoDB
using Node.js
Prerequisites
•Install Node.js (from nodejs.org)
•Install MongoDB (from mongodb.com)
•Install Dependencies:
npm install mongodb express
Connecting to MongoDB
const { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
async function connectDB() {
await client.connect();
console.log("Connected to MongoDB");
return client.db("testDB");
}
Inserting Data into MongoDB
const connectDB = require("./database");
async function insertData() {
const db = await connectDB();
const usersCollection = db.collection("users");
const newUser = { name: "John Doe", email: "john@example.com", age: 30 };
const result = await usersCollection.insertOne(newUser);
console.log("Inserted document ID:", result.insertedId);
}
insertData();
Retrieving Data from MongoDB
const connectDB = require("./database");//expected to establish a connection to a database.
async function getUsers() { //handling asynchronous operations.
const db = await connectDB();//waits for the connection to be established.
const usersCollection = db.collection("users");//Retrieves the "users" collection from the database.
const users = await usersCollection.find({}).toArray();//Executes a query to find all documents
(records) in the "users" collection.
console.log("Users:", users); //Prints the retrieved user data to the console.
}
getUsers(); //function to execute the database query and print the results.
Handling SQL Databases from Node.js
Introduction
•What is an SQL Database?
• Structured data storage using tables
• Examples: MySQL, PostgreSQL, SQLite
•Why Use Node.js with SQL?
• Build scalable applications
• Perform CRUD operations
Prerequisites
•Install Node.js from nodejs.org
•Install database (MySQL, PostgreSQL, or
SQLite)
•Install necessary npm packages:
•MySQL: npm install mysql2
•PostgreSQL: npm install pg
•SQLite: npm install sqlite3
Connecting to Database
const mysql = require("mysql2");// package is required to interact with a MySQL database.
const connection = mysql.createConnection({ //creates a connection to the MySQL database.
host: "localhost", //The database is hosted locally.
user: "root", //The username for the database.
password: "password", //The password for the database (this should not be hardcoded in a real
application).
database: "testdb“ //The name of the database to connect to.
});
connection.connect(err => { //method establishes the connection.
if (err) throw err; //If an error occurs during the connection, it is thrown
console.log("Connected to MySQL!");});
Creating a Table
SQL Query to Create Users Table
const sql = `CREATE TABLE IF NOT EXISTS users //ensures that the "users" table
is created only if it does not already exist.
( id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100), //to store the user’s name.
email VARCHAR(100), //to store the user’s email.
age INT)`;//An integer to store the user’s age.
connection.query(sql, err => { //executes the SQL query using the MySQL connection.
if (err) throw err; //If error occurs stops execution and logs the error.
console.log("Table created successfully!");
});
// A unique integer (INT) that auto-increments with each new row.
It is the primary key.
Inserting Data
SQL Query to Insert Data
const sql = "INSERT INTO users (name, email, age) VALUES (?, ?, ?)"; //This is an SQL
INSERT statement that inserts data into the
const values = ["John Doe", "john@example.com", 30];
connection.query(sql, values, (err, result) => {
if (err) throw err; //If error occurs stops execution and logs the error.
console.log("Data inserted successfully!", result.insertId);
});
Retrieving Data
SQL Query to Retrieve Data
connection.query("SELECT * FROM users", (err, results) => {
if (err) throw err; //If error occurs stops execution and logs the error
console.log("Users:", results);
});
SQL Query to Update Data
const sql = "UPDATE users SET age = ? WHERE name = ?";
const values = [35, "John Doe"];
connection.query(sql, values, (err, result) => {
if (err) throw err; //If error occurs stops execution and logs the error.
console.log("Data updated successfully!");
});
SQL Query to Delete Data
const sql = "DELETE FROM users WHERE name = ?";
connection.query(sql, ["John Doe"], (err, result) => {
if (err) throw err; //If error occurs stops execution and logs the error
console.log("Data deleted successfully!");
});
Handling Cookies in Node.js
Introduction
•What are Cookies?
• Small pieces of data stored in the browser.
• Used for session management, personalization, and tracking.
Setting Cookies in Node.js (Without Express)
const http = require('http’);//Allow us to create a HTTP Server
const server = http.createServer((req, res) => {//creates an HTTP server.
res.setHeader('Set-Cookie', 'username=JohnDoe; HttpOnly; Max-Age=3600’); //This sets an
HTTP cookie in the response
res.end('Cookie set’);//signaling that the cookie has been set.
});
server.listen(3000);
Reading Cookies in Node.js
const parseCookies = (cookieHeader) => { //A string containing
cookies
return cookieHeader
? Object.fromEntries(cookieHeader.split('; ').map(c =>
c.split('=‘)))//converts an array of key-value pairs into a JavaScript object.
// cookieHeader.split('; '). Splits the cookie string at =,creating
an array of key-value pairs
: {};
};
Using Express.js for Cookie Handling
npm install express cookie-parser // express → A framework to create web servers easily.
cookie-parser → A middleware to parse cookies from incoming requests
const express = require('express');
const cookieParser = require('cookie-parser’); // import cookie-parser middleware to handle cookies.
const app = express(); //Initializes an Express application.
app.use(cookieParser()); //Enables cookie parsing for all incoming requests.
app.get('/set-cookie', (req, res) => { //When a client visits
res.cookie('username', 'JohnDoe', { httpOnly: true, maxAge: 3600000 }); // httpOnly: The cookie
cannot be accessed by JavaScript (for security).
//The cookie expires in 1 hour (3600000 ms).
res.send('Cookie set’);
});
app.get('/get-cookie', (req, res) => {
res.send(req.cookies); //Contains all cookies sent by the client.
});
•.
// When a client visits /get-cookie, this route reads cookies from the request.
THANK YOU

24CA206 Full Stack Web Development mongodb

  • 1.
    ROHINI COLLEGE OFENGINEERING& TECHNOLOGY 24CA206-FULL STACK WEB DEVELOPMENT I YEAR-IISEM –COMPUTER APPLICATION By, Mrs. R.S.RAMYA DEVI
  • 2.
    Adding and RetrievingData in MongoDB with Node.js •What is MongoDB? A NoSQL database for storing JSON-like documents •What is Node.js? A JavaScript runtime for building backend applications •Purpose of the Presentation How to connect, insert, and retrieve data in MongoDB using Node.js
  • 3.
    Prerequisites •Install Node.js (fromnodejs.org) •Install MongoDB (from mongodb.com) •Install Dependencies: npm install mongodb express
  • 4.
    Connecting to MongoDB const{ MongoClient } = require("mongodb"); const uri = "mongodb://localhost:27017"; const client = new MongoClient(uri); async function connectDB() { await client.connect(); console.log("Connected to MongoDB"); return client.db("testDB"); }
  • 5.
    Inserting Data intoMongoDB const connectDB = require("./database"); async function insertData() { const db = await connectDB(); const usersCollection = db.collection("users"); const newUser = { name: "John Doe", email: "john@example.com", age: 30 }; const result = await usersCollection.insertOne(newUser); console.log("Inserted document ID:", result.insertedId); } insertData();
  • 6.
    Retrieving Data fromMongoDB const connectDB = require("./database");//expected to establish a connection to a database. async function getUsers() { //handling asynchronous operations. const db = await connectDB();//waits for the connection to be established. const usersCollection = db.collection("users");//Retrieves the "users" collection from the database. const users = await usersCollection.find({}).toArray();//Executes a query to find all documents (records) in the "users" collection. console.log("Users:", users); //Prints the retrieved user data to the console. } getUsers(); //function to execute the database query and print the results.
  • 7.
    Handling SQL Databasesfrom Node.js Introduction •What is an SQL Database? • Structured data storage using tables • Examples: MySQL, PostgreSQL, SQLite •Why Use Node.js with SQL? • Build scalable applications • Perform CRUD operations
  • 8.
    Prerequisites •Install Node.js fromnodejs.org •Install database (MySQL, PostgreSQL, or SQLite) •Install necessary npm packages: •MySQL: npm install mysql2 •PostgreSQL: npm install pg •SQLite: npm install sqlite3
  • 9.
    Connecting to Database constmysql = require("mysql2");// package is required to interact with a MySQL database. const connection = mysql.createConnection({ //creates a connection to the MySQL database. host: "localhost", //The database is hosted locally. user: "root", //The username for the database. password: "password", //The password for the database (this should not be hardcoded in a real application). database: "testdb“ //The name of the database to connect to. }); connection.connect(err => { //method establishes the connection. if (err) throw err; //If an error occurs during the connection, it is thrown console.log("Connected to MySQL!");});
  • 10.
    Creating a Table SQLQuery to Create Users Table const sql = `CREATE TABLE IF NOT EXISTS users //ensures that the "users" table is created only if it does not already exist. ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), //to store the user’s name. email VARCHAR(100), //to store the user’s email. age INT)`;//An integer to store the user’s age. connection.query(sql, err => { //executes the SQL query using the MySQL connection. if (err) throw err; //If error occurs stops execution and logs the error. console.log("Table created successfully!"); }); // A unique integer (INT) that auto-increments with each new row. It is the primary key.
  • 11.
    Inserting Data SQL Queryto Insert Data const sql = "INSERT INTO users (name, email, age) VALUES (?, ?, ?)"; //This is an SQL INSERT statement that inserts data into the const values = ["John Doe", "john@example.com", 30]; connection.query(sql, values, (err, result) => { if (err) throw err; //If error occurs stops execution and logs the error. console.log("Data inserted successfully!", result.insertId); });
  • 12.
    Retrieving Data SQL Queryto Retrieve Data connection.query("SELECT * FROM users", (err, results) => { if (err) throw err; //If error occurs stops execution and logs the error console.log("Users:", results); }); SQL Query to Update Data const sql = "UPDATE users SET age = ? WHERE name = ?"; const values = [35, "John Doe"]; connection.query(sql, values, (err, result) => { if (err) throw err; //If error occurs stops execution and logs the error. console.log("Data updated successfully!"); });
  • 13.
    SQL Query toDelete Data const sql = "DELETE FROM users WHERE name = ?"; connection.query(sql, ["John Doe"], (err, result) => { if (err) throw err; //If error occurs stops execution and logs the error console.log("Data deleted successfully!"); });
  • 14.
  • 15.
    Introduction •What are Cookies? •Small pieces of data stored in the browser. • Used for session management, personalization, and tracking. Setting Cookies in Node.js (Without Express) const http = require('http’);//Allow us to create a HTTP Server const server = http.createServer((req, res) => {//creates an HTTP server. res.setHeader('Set-Cookie', 'username=JohnDoe; HttpOnly; Max-Age=3600’); //This sets an HTTP cookie in the response res.end('Cookie set’);//signaling that the cookie has been set. }); server.listen(3000);
  • 16.
    Reading Cookies inNode.js const parseCookies = (cookieHeader) => { //A string containing cookies return cookieHeader ? Object.fromEntries(cookieHeader.split('; ').map(c => c.split('=‘)))//converts an array of key-value pairs into a JavaScript object. // cookieHeader.split('; '). Splits the cookie string at =,creating an array of key-value pairs : {}; };
  • 17.
    Using Express.js forCookie Handling npm install express cookie-parser // express → A framework to create web servers easily. cookie-parser → A middleware to parse cookies from incoming requests const express = require('express'); const cookieParser = require('cookie-parser’); // import cookie-parser middleware to handle cookies. const app = express(); //Initializes an Express application. app.use(cookieParser()); //Enables cookie parsing for all incoming requests. app.get('/set-cookie', (req, res) => { //When a client visits res.cookie('username', 'JohnDoe', { httpOnly: true, maxAge: 3600000 }); // httpOnly: The cookie cannot be accessed by JavaScript (for security). //The cookie expires in 1 hour (3600000 ms). res.send('Cookie set’); }); app.get('/get-cookie', (req, res) => { res.send(req.cookies); //Contains all cookies sent by the client. }); •. // When a client visits /get-cookie, this route reads cookies from the request.
  • 18.