Lesson 4
Deleting Records by ID with Mongoose
Deleting Records by ID with Mongoose

Welcome to the lesson on "Deleting Records by ID" using Mongoose! In this lesson, we will learn how to remove a specific record from our MongoDB database based on its unique ID. This skill is vital for database maintenance, such as cleaning up outdated, irrelevant, or incorrect data.

What You'll Learn

In this lesson, you'll learn how to:

  • Set up a Mongoose model and establish a connection to a MongoDB database.
  • Define a schema and model for ToDo items to structure your data effectively.
  • Implement a route to delete a ToDo item by its unique ID.
  • Handle potential errors during the deletion process to ensure the application runs smoothly.
Step 1: Setting up Express and Connecting to MongoDB

Let's quickly set up an Express server and connect it to our MongoDB instance.

JavaScript
1const express = require('express'); 2const mongoose = require('mongoose'); 3 4const app = express(); 5const PORT = 3000; 6 7// Connect to MongoDB 8mongoose.set('strictQuery', true); 9mongoose.connect('mongodb://127.0.0.1:27017/todo-app', { 10 useNewUrlParser: true, 11 useUnifiedTopology: true 12}).then(() => { 13 console.log('Connected to MongoDB'); 14}).catch((error) => { 15 console.error('Connection error', error); 16 process.exit(1); 17});

This code imports the necessary libraries, sets up an Express application, and connects to a MongoDB instance named todo-app.

Step 2: Defining a Schema and Model for ToDo Items

Now we'll define a schema and model for our ToDo items.

JavaScript
1// Define a schema and model for ToDo items 2const todoSchema = new mongoose.Schema({ 3 task: { type: String, required: true }, 4 completed: { type: Boolean, default: false } 5}); 6 7const Todo = mongoose.model('Todo', todoSchema);

We define a todoSchema with task and completed fields and create a Todo model from it. This model will help us interact with ToDo items in the MongoDB database.

Step 3: Implementing a Route to Delete a ToDo by ID

We'll implement a route to delete a ToDo item by its unique ID. This functionality is crucial for managing and maintaining data integrity in our application by allowing us to remove records that are no longer needed.

JavaScript
1// Route to delete a todo by ID 2app.delete('/todos/:id', async (req, res) => { 3 const { id } = req.params; 4 5 try { 6 const todo = await Todo.findByIdAndDelete(id); 7 if (!todo) return res.status(404).json({ message: 'Todo not found' }); 8 res.json({ message: 'Todo deleted' }); 9 } catch (error) { 10 res.status(500).json({ message: 'Failed to delete todo' }); 11 } 12});

In this code, we set up a DELETE route at /todos/:id to handle requests for deleting a ToDo item by its ID. We extract the ID parameter from the request and use findByIdAndDelete to attempt to delete the corresponding ToDo item. If the item is found and successfully deleted, we return a success message. If no item is found, we return a 404 status with an appropriate message. Any errors during the operation are caught and handled by returning a 500 status with a failure message.

Step 4: Starting the Server

Finally, we'll start the server to listen on the defined port. This step is necessary to run our application and make it accessible for handling client requests.

JavaScript
1app.listen(PORT, () => { 2 console.log(`Server running on http://localhost:${PORT}`); 3});

In this code, we call app.listen to start the server on the specified port. A message is logged to confirm that the server is running and accessible via the defined URL, indicating that our application is ready to handle incoming requests.

Conclusion

In this lesson, we've set up an Express server, connected it to a MongoDB instance using Mongoose, defined a schema and model for ToDo items, implemented a route to delete ToDo items by ID, and handled potential errors during the deletion process. These steps are foundational for building robust applications that can effectively manage and maintain data integrity.

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.