In this lesson, we will expand on our todo app functionality by learning how to update and delete ToDo items using Mongoose with Express.js. By the end of this lesson, you'll be able to modify existing tasks and remove them from the database, completing the full CRUD (Create, Read, Update, Delete) cycle for managing your ToDo items.
In this lesson, you'll learn:
- How to set up the todo schema and model.
- How to update an existing todo item.
- How to delete a todo item.
- How to implement these actions via API routes in Express.
Before learning how to update and delete ToDo items, let's first set up the ToDo schema and model, which define the data structure and enable database interaction.
JavaScript1const todoSchema = new mongoose.Schema({ 2 task: { type: String, required: true } // task is a required string 3}); 4 5const Todo = mongoose.model('Todo', todoSchema); // create Todo model using the schema
The schema acts as a blueprint, defining the structure and requirements for our data. Think of the schema as a blueprint for building a house. It defines the type and constraints of each field. In our case, the task field is a string and is required.
The model, on the other hand, enables CRUD (Create, Read, Update, Delete) operations on the database. The model is like a set of methods and properties that allow us to interact with our schema in meaningful ways, enabling us to perform database operations seamlessly.
We'll start by adding functionality to update a ToDo item. We'll create an API route that allows us to modify a todo task by its ID.
JavaScript1app.put('/todos/:id', async (req, res) => { 2 const { id } = req.params; 3 const { task, status } = req.body; 4 5 try { 6 const updatedTodo = await Todo.findByIdAndUpdate(id, { task, status }, { new: true, runValidators: true }); 7 if (!updatedTodo) { 8 return res.status(404).send({ message: 'Todo not found' }); 9 } 10 res.status(200).send(updatedTodo); 11 } catch (err) { 12 res.status(400).send({ error: 'Error updating Todo: ' + err.message }); 13 } 14});
Here, we:
- Define a
PUT
route/todos/:id
to handle updates to specific todo items, identified by theirid
. - Use
findByIdAndUpdate
to locate the todo item by ID and update it with the new task and status. - Ensure
runValidators
is set totrue
to enforce schema validation. - If the todo item is successfully updated, we return it with a 200 status code.
- If the item does not exist or there’s an error, we return appropriate error messages.
Next, let's create an API route to delete a ToDo item by its ID.
JavaScript1app.delete('/todos/:id', async (req, res) => { 2 const { id } = req.params; 3 4 try { 5 const deletedTodo = await Todo.findByIdAndDelete(id); 6 if (!deletedTodo) { 7 return res.status(404).send({ message: 'Todo not found' }); 8 } 9 res.status(200).send({ message: 'Todo deleted successfully' }); 10 } catch (err) { 11 res.status(400).send({ error: 'Error deleting Todo: ' + err.message }); 12 } 13});
This code:
- Defines a
DELETE
route/todos/:id
to handle deletion of specific todo items. - Uses
findByIdAndDelete
to locate the item by ID and remove it from the database. - If the item is deleted, a success message is returned.
- If the item cannot be found or if there’s an error, we return appropriate status codes and error messages.
In this lesson, we completed the CRUD cycle by adding the ability to update and delete todo items. We covered how to set up API routes in Express to handle these operations with Mongoose. With these capabilities, you can now fully manage your ToDo list, modifying and removing items as needed.
This lays the foundation for more complex applications where data management is crucial. Practice these concepts by building more advanced features, such as user authentication or filtering tasks based on status.