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.
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.
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.
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.
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.
