Build a CRUD App with Node.js, MongoDB, and Next.js
To implement a basic CRUD (Create, Read, Update, Delete) application in Node.js using Next.js and MongoDB, follow these steps:
Step 1: Set up a Next.js project
Create a Next.js project (if you haven't already):
Install necessary dependencies:
Step 2: Set up MongoDB connection
Create a
.env.local
file in the root of your project and add your MongoDB connection string:Create a utility file to manage the MongoDB connection. Create a new file
lib/mongodb.js
:
Step 3: Create a Mongoose Model
Define a model for the data you want to store in MongoDB. For example, let's create a simple model for User
.
Create a new file models/User.js
:
Step 4: Create API Routes for CRUD Operations
Next.js allows you to create API routes easily. Here’s how you can implement the CRUD operations.
1. Create User (/pages/api/users/create.js
)
2. Read Users (/pages/api/users/index.js
)
3. Update User (/pages/api/users/[id].js
)
4. Delete User (/pages/api/users/[id].js
)
Step 5: Test CRUD Operations
Create a user:
Send a POST request to
/api/users/create
with the user data in the body:Read users:
Send a GET request to
/api/users
.Update a user:
Send a PUT request to
/api/users/[id]
with the updated data in the body:Delete a user:
Send a DELETE request to
/api/users/[id]
.
Step 6: Run the Application
Now, run the Next.js application:
You can access the API routes and interact with the MongoDB database to perform CRUD operations.
This is a basic setup for a CRUD app using Next.js and MongoDB. You can extend it with features like validation, authentication, and error handling as needed.