Database Integration:
Extend the previous Node.js server by integrating a database (e.g., SQLite or
MongoDB).
Implement endpoints to perform CRUD operations on a dataset.
// Import necessary modules
const express = require("express"); // Express framework for building web
applications
const mongoose = require("mongoose"); // Mongoose for MongoDB object modeling
const app = express(); // Create an instance of Express application
const PORT = process.env.PORT || 3000; // Set the port for the server, use
environment variable or default to 3000
// Middleware to parse incoming JSON requests
app.use(express.json());
// Connect to MongoDB
mongoose.connect("mongodb://localhost:27017/MCE2", { // Connect to the MongoDB
database named "MCE2"
useNewUrlParser: true, // Use new URL parser
useUnifiedTopology: true, // Use new Server Discovery and Monitoring engine
})
.then(()=>{
console.log("Connection to DB Successful !"); // Log success message if
connection is successful
})
.catch((err)=>{
console.log("Connection to DB Failed !"); // Log error message if connection
fails
})
// Define a mongoose schema for the data
const dataSchema = new mongoose.Schema({
name: String,
usn: String,
sem: String
});
// Create a mongoose model based on the schema
const Data = mongoose.model("Data", dataSchema);
// Define a route for the root endpoint
app.get("/", (req, res) => {
res.send("Home"); // Respond with "Home" when the root endpoint is accessed
});
// Retrieve all data from MongoDB
app.get("/api/data", async (req, res) => {
try {
const allData = await Data.find(); // Retrieve all data entries from the "Data"
collection in MongoDB
res.json(allData); // Respond with the retrieved data in JSON format
} catch (err) {
console.error(err);
res.status(500).json({ message: "Internal Server Error" }); // Handle errors
and respond with an internal server error
}
});
// Create a new data entry in MongoDB
app.post('/api/data', async (req, res) => {
try {
const nItem = req.body; // Get the data from the request body
const newData = new Data(nItem); // Create a new instance of the Data model
with the received data
await newData.save(); // Save the new data entry to the MongoDB collection
res.json(newData); // Respond with the saved data in JSON format
} catch (err) {
console.error(err);
res.status(500).json({ message: "Internal Server Error" }); // Handle errors
and respond with an internal server error
}
});
// Update data by ID in MongoDB (This part is missing in the provided code)
// Start the server and listen on the specified port
app.listen(PORT, (err) => {
if (err) console.log(err); // Log any errors that occur while starting the server
console.log("Server running on port: ", PORT); // Log a message indicating that
the server is running on the specified port
});