In this lesson, we'll learn how to update records in a MongoDB collection using Mongoose. Updating records is essential for maintaining accurate and useful data in an application.
You'll learn
- how to set up a MongoDB connection using Mongoose,
- create a schema and model for a MongoDB collection,
- update a document by its ID,
- handle potential errors during the update process.
Let's start by setting up a connection to MongoDB using Mongoose. This is important because it establishes a link between our application and the database, allowing us to perform operations like updates.
JavaScript1const express = require('express'); 2const mongoose = require('mongoose'); 3 4const app = express(); 5const PORT = 3000; 6 7// Set mongoose strictQuery to true to suppress deprecation warning 8mongoose.set('strictQuery', true); 9 10// Connect to MongoDB 11mongoose.connect('mongodb://127.0.0.1:27017/todo-app', { 12 useNewUrlParser: true, 13 useUnifiedTopology: true 14}).then(() => { 15 console.log('Connected to MongoDB'); 16}).catch((error) => { 17 console.error('Connection error', error); 18}); 19 20app.use(express.json());
In this code, we start by importing express
and mongoose
. We then set up an Express application and define the port number. Next, we configure mongoose
to suppress a deprecation warning with mongoose.set('strictQuery', true)
. We connect to the MongoDB database using mongoose.connect
, providing the connection string and options. A successful connection logs "Connected to MongoDB" to the console, while an error logs the connection error. Finally, we use app.use(express.json())
to enable JSON parsing of request bodies.
Now we'll define a schema and model for our "ToDo" items in the database. This is helpful for structuring data and interacting with it in a consistent manner.
JavaScript1// 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);
In this code, we define todoSchema
to specify the structure of a "ToDo" item, with fields task
and completed
. The task
field is a required string, and the completed
field is a boolean that defaults to false
. We then create the Todo
model from this schema, which allows us to interact with the "ToDo" collection in the database.
Let's create a route to update a to-do item by its ID. This is important for handling HTTP requests and integrating our update functionality into a web server.
JavaScript1// Route to update a todo by ID 2app.put('/todos/:id', async (req, res) => { 3 const { id } = req.params; 4 const { task, completed } = req.body; 5 6 try { 7 const updatedTodo = await Todo.findByIdAndUpdate(id, { task, completed }, { new: true }); 8 if (!updatedTodo) return res.status(404).json({ message: 'Todo not found' }); 9 res.json(updatedTodo); 10 } catch (error) { 11 res.status(400).json({ message: 'Failed to update todo' }); 12 } 13});
In this code, we set up a PUT
route to handle updates to "ToDo" items by their ID. The route receives the id
from the URL parameters and the updated task
and completed
fields from the request body. The Todo.findByIdAndUpdate
method is used to find the "Todo" item by ID and update it with new data. The { new: true }
option returns the updated document. If the document is not found, a 404 response is returned. If an error occurs, a 400 response is returned with a failure message.
Lastly, let's start our server and listen for incoming requests. This is important to ensure that our application is running and can handle updates.
JavaScript1app.listen(PORT, () => { 2 console.log(`Server running on http://localhost:${PORT}`); 3});
In this code, we use app.listen
to start the Express server on the specified port (3000) and log a message to the console indicating that the server is running.
By the end of this lesson, you have learned how to set up a MongoDB connection, create a schema and model, and update a document by its ID using Mongoose. You also know how to handle potential errors during the update process, ensuring the application remains robust.