Course

Find Documents - Exercise

In the previous lesson, you learned how to find documents in a collection using Mongoose. Now, it's time to practice what you've learned.

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

If you've already followed those lessons, you should know how this works

In order to interact with our database, we need to follow a few crucial steps.

  1. Create a file in the actions folder hold our server actions. In this case, we already have a user.actions.ts file.

  2. Import the necessary models and dependencies. In this case, we'll need to import the User model and the connect function from db.ts.

  3. Create a function that will interact with the database. In this case, we'll create a function that will find a user by their name.

  4. Export the function so we can use it in our application.

Now, let's get started with the exercise.

Exercise

Let's open up our user.actions.ts file and create a function that will find a user by their name.

Let's name this function findUserByName, and make sure we connect to the database before we run the query.

import User from "@/lib/models/user";

user.actions.ts;

export async function findUserByName(name: string) {
  await dbConnect();
  // todo: find user by name
}

Using what you've learned from the previous lesson, complete the findUserByName function to find a user by their name.

Hint
monkey
import User from "@/lib/models/user";

user.actions.ts;

export async function findUserByName(name: string) {
  await dbConnect();
  const user = await User.find({ name });
  return user;
}

Once you've completed the function, you should be able to import it into your application and use it to find a user by their name.

Give it a shot!

Conclusion

In this exercise, you learned how to find documents in a collection using Mongoose. You created a function that finds a user by their name and exported it so you can use it in your application.

In the next lesson, you'll learn more advanced methods of updating documents in a collection using Mongoose.

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

Find Documents in Mongoose - More Find Methods