Course

Update Documents - Exercise

In the previous lessons, we learned how to find documents in Mongoose. In this exercise we will practice updating documents.

Exercise

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:

app
lib
actions
user.actions.ts
models
user.ts
db.ts
Insight

If you've missed the setup and need to catch up, you can check out these lessons:

Setting Up



Creating Models

Practice

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.

  1. Open the user.actions.ts file.

  2. Create a new function called updateUserEmail that takes two parameters: userId and newEmail.

  3. Inside the function, use the User model to find and update the user's email.

Hint
monkey
//
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;
};

Conclusion

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.

0 Comments

"Please login to view comments"

glass-bbok

Join the Conversation!

Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.

Upgrade your account
tick-guideNext Lesson

Updating Documents - Operators