Course

Creating a Models and Actions

In this lesson, we'll create a basic model and a basic server action to interact with our database. We'll start by creating a connection file to connect to our database inside our Next.js app.

Create a basic model

Now that we have our connection file set up, we can create a basic model. We'll create a model for a user. This is only an example, but will be a good starting point to understand how we structure our files and models.

Create a file called user.ts in the models folder:

app
lib
models
user.ts
db.ts

Next, we'll create a basic for our user model:

import { Document, model, Schema } from "mongoose";

user.ts;

// define the user interface for typescript
interface User {
  name: string;
  email: string;
}

// create the user schema
const UserSchema = new Schema<User>({
  name: String,
  email: String,
});

This just creates our user schema. We're defining the shape of our user object. We're saying that a user has a name and an email. Remember to create a model, we first create our schema, and then we pass that schema to the model function from .

import { Document, model, Schema } from "mongoose";

user.ts;

interface User {
  name: string;
  email: string;
}

const UserSchema = new Schema<User>({
  name: String,
  email: String,
});

const User = model<User>("User", UserSchema);
export default User;

This code creates a model called User and exports it. We can now use this model in other files to interact with our database.

But just like with our connection file, we need to make sure that our model is only created once. We don't want to create a new model every time we import it. We only want to create it once and then use that instance everywhere else.

To do this, we can just check to see if the model already exists before creating it. If it does, we can just return the existing model. If it doesn't, we can create it and then return it.

import { Document, model, models, Schema } from "mongoose";

user.ts;

interface User {
  name: string;
  email: string;
}

const UserSchema = new Schema<User>({
  name: String,
  email: String,
});

// return mongoose's model if it exists
// otherwise create a new model
const User = models?.User || model<User>("User", UserSchema);

export default User;
Insight

When running your development server and making changes to your models, you may need to restart your server to see the changes reflected in your database.

So if you've made changes to your model and you're not seeing those changes reflected in your database, try restarting your development server!

Create a basic server action

Now that we have our model set up, we can create a basic server action to interact with our database. We'll create a couple basic actions to create a new user and get all users.

When you want to interact with your database in a server action, you'll need to import two things:

  1. Your model
  2. Your connection

We'll start by creating a basic action to create a new user. Create a file called user.actions.ts in the actions folder:

app
lib
actions
user.actions.ts
models
user.ts
db.ts
import User from "@/lib/models/user";

user.actions.ts;

export async function createUser(name: string, email: string) {
  // make sure we're connected to the database
  // before doing anything!
  await dbConnect();

  // create a new user
  const user = await User.create({ name, email });
  return user;
}
Insight

Here, we're using the method for the example, so that we have some data. If you'd like to learn more about the method, you can check out

this lesson

.

Next we'll create a function to grab all of our users! Can you figure out the code we need to write that function? You can look back at The previous lesson for a hint!

Hint
monkey

user.actions.ts

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

export async function createUser(name: string, email: string) {
  // ...
}

export async function getAllUsers() {
  // always make sure we're connected
  await dbConnect();
  // use the find method to get all users
  const users = await User.find();
  return users;
}

In the following lessons, we'll address all of the ways we can interact with our database using Mongoose, and how we can expand on these "find" methods. For now- we're just setting up our basic structure.

Give it a try!

Go ahead and import your createUser and getAllUsers functions into a page and give them a try! You can use the createUser function to create a new user, and the getAllUsers function to get all users from your database.

Here, I'm just modifying the default page that Next.js gives you when you create a new project.

//
import { createUser, getAllUsers } from "@/lib/actions/user";

export default async function Page() {
  // Create a new user
  await createUser("Alice", "alice@email.com");
  // Get all users
  const users = await getAllUsers();
  console.log(users);
}

You should see the list of all users in your console:

//
[
  {
    _id: new ObjectId('664a9f76281627927478725d'),
    name: 'Alice',
    email: 'alice@email.com',
    __v: 0
  }
]

Conclusion

In this lesson, we created a basic model and a basic server action to interact with our database. We created a model for a user, and then created a couple of actions to create a new user and get all users. We also made sure that our model is only created once, so we don't create a new model every time we import it.

In the following lessons, we'll dive into how to interact with our database using more advanced methods and queries.

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

Creating Models and Actions: Exercise