0% found this document useful (0 votes)
19 views4 pages

Node 5

This worksheet outlines the steps to use Mongoose for connecting to a MongoDB database and performing CRUD operations on employee records. It includes code examples for creating, reading, updating, and deleting employee data, as well as handling user input in a Node.js application. The learning outcomes emphasize understanding Mongoose schemas, managing database connections, and implementing error handling.

Uploaded by

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

Node 5

This worksheet outlines the steps to use Mongoose for connecting to a MongoDB database and performing CRUD operations on employee records. It includes code examples for creating, reading, updating, and deleting employee data, as well as handling user input in a Node.js application. The learning outcomes emphasize understanding Mongoose schemas, managing database connections, and implementing error handling.

Uploaded by

Keshav Gangwar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

BACK-END TECHNOLOGY

Worksheet No - 05
Student Name: Keshav Kumar UID: 23MCA20462
Branch: MCA Section: 23MCA-8A
Semester : III DOP : 25/09/2024
Subject Name: Back-end technology Subject Code: 23CAH-705

Aim:
The objective of this worksheet is to understand how to use Mongoose to connect to a MongoDB database
and perform CRUD (Create, Read, Update, Delete) operations. Mongoose simplifies interactions with
MongoDB by providing a schema-based solution to model application data.

Steps for Implementation:


1. Install Dependencies
2. Set Up MongoDB
3. Create Mongoose Connection
Code
const mongoose = require("mongoose");
const readline = require("readline");
// Connection URL
const url = "mongodb://localhost:27017/EmployeeDB";
// Create a Mongoose schema for Employee
const employeeSchema = new mongoose.Schema(
{
empId: Number,
name: String,
position: String,
salary: Number,
},
{ versionKey: false }
);
// Create a Mongoose model
const Employee = mongoose.model("Employee", employeeSchema);

// Connect to the MongoDB server


async function connect() {
try {
await mongoose.connect(url);
console.log("Connected successfully to MongoDB server");
} catch (err) {
console.error("Error connecting to MongoDB:", err);
throw err;
}
}
// Create (Insert) an employee
async function createEmployee(employee) {
try {
const newEmployee = new Employee(employee);
const result = await newEmployee.save();
console.log(`Inserted employee with ID: ${result._id}`);
return result._id;
} catch (err) {
console.error("Error creating employee:", err);
throw err;
}
}
// Read (Retrieve) an employee by ID
async function getEmployeeById(id) {
try {
const employee = await Employee.findOne({ empId: id });
if (employee) {
console.log("Employee found:", employee);
} else {
console.log("No employee found with that ID");
}
return employee;
} catch (err) {
console.error("Error retrieving employee:", err);
throw err;
}
}
// Update an employee
async function updateEmployee(id, updatedData) {
try {
const result = await Employee.findOneAndUpdate({ empId: id }, updatedData, {
new: true,
});
if (result) {
console.log("Employee updated:", result);
return 1;
} else {
console.log("No employee found with that ID");
return 0;
}
} catch (err) {
console.error("Error updating employee:", err);
throw err;
}
}
// Delete an employee
async function deleteEmployee(id) {
try {
const result = await Employee.findOneAndDelete({ empId: id });
if (result) {
console.log("Employee deleted:", result);
return 1;
} else {
console.log("No employee found with that ID");
return 0;
}
} catch (err) {
console.error("Error deleting employee:", err);
throw err;
}
}
// Function to get user input
function getUserInput(question) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) => {
rl.question(question, (answer) => {
rl.close();
resolve(answer);
});
});
}

// Main function to handle user choices


async function main() {
await connect();
while (true) {
console.log("\nEmployee Management System");
console.log("1. Create Employee");
console.log("2. Read Employee");
console.log("3. Update Employee");
console.log("4. Delete Employee");
console.log("5. Exit");

const choice = await getUserInput("Enter your choice (1-5): ");

switch (choice) {
case "1":
const empId = await getUserInput("Enter employee ID: ");
const name = await getUserInput("Enter employee name: ");
const position = await getUserInput("Enter employee position: ");
const salary = await getUserInput("Enter employee salary: ");
const newEmployeeId = await createEmployee({
empId: parseInt(empId),
name,
position,
salary: parseInt(salary),
});
console.log(`New employee created with ID: ${newEmployeeId}`);
break;
case "2":
const readId = await getUserInput("Enter employee ID to read: ");
await getEmployeeById(parseInt(readId));
break;
case "3":
const updateId = await getUserInput("Enter employee ID to update: ");
const updateField = await getUserInput(
"Enter field to update (empId/name/position/salary): "
);
const updateValue = await getUserInput("Enter new value: ");
const updateData = {
[updateField]:
updateField === "salary" || updateField === "empId"
? parseInt(updateValue)
: updateValue,
};
await updateEmployee(parseInt(updateId), updateData);
break;
case "4":
const deleteId = await getUserInput("Enter employee ID to delete: ");
await deleteEmployee(parseInt(deleteId));
break;
case "5":
console.log("Exiting the program.");
await mongoose.connection.close();
return;
default:
console.log("Invalid choice. Please try again.");
}
}
}
main();
Output:

Learning Outcomes:-
- Learn how to define a Mongoose schema for employee records.
- Understand how to create a Mongoose model to interact with MongoDB.
- Establish a connection to a MongoDB database using Mongoose.
- Perform CRUD operations on employee records in MongoDB.
- Insert new employee records into the database.
- Retrieve specific employee data based on `empId`.
- Update specific fields of an employee record using `empId`.
- Delete employee records from the database using `empId`.
- Handle user input using the `readline` module in Node.js.
- Use `async/await` for performing asynchronous database operations.
- Dynamically update specific fields in a MongoDB document based on user input.
- Manage error handling during database interactions.
- Practice structuring a Node.js application with modular code for CRUD operations.

Sign………………….

You might also like