
Join the Conversation!
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.
In the previous lessons, we learned how to find documents in Mongoose. In this exercise we will practice updating documents.
If you've been following along, you should already have a basic folder structure and a file for storing our actions. Your structure should look something like this:
If you've missed the setup and need to catch up, you can check out these lessons:
Setting Up
Creating Models
To practice updating documents in Mongoose, we will create a new action in our user.actions.ts file. This action will update a user's email address.
Open the user.actions.ts file.
Create a new function called updateUserEmail that takes two parameters: userId and newEmail.
Inside the function, use the User model to find and update the user's email.
//
import dbConnect from "@/lib/db";
import User from "@/lib/models/user";
export const updateUserEmail = async (userId: string, newEmail: string) => {
await dbConnect();
const user = await User.updateOne({ _id: userId }, { email: newEmail });
return user;
};
In this exercise, we practiced updating documents in Mongoose. We created a new action to update a user's email address. In the next lesson, we will learn more advanced methods of updating models using operators.
"Please login to view comments"
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.