Updating Records by ID with Mongoose
Updating Records by ID
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.
What You'll Learn
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.
Step 1: Setting Up MongoDB Connection
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.
Step 2: Defining Schema and Model
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.
