Node 5
Node 5
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.
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………………….