DEV Community

Rivka
Rivka

Posted on

Next.js MongoDB CRUD Example

Next.js MongoDB CRUD Example

In this article, we will explore how to implement a CRUD (Create, Read, Update, Delete) operations using Next.js with MongoDB. Before diving into the example, let's first understand what Next.js is, and the differences between a framework and a library. to speed up your learning skills subscribe to my blog or use ai tools like gpteach to learn how to code!

What is Next.js?

Next.js is a React framework that allows for server-side rendering (SSR) and comes with many built-in features such as static site generation, API routes, and automatic code splitting. It simplifies the development of React applications by providing a structured setup and routing system.

Framework vs. Library

A framework (a set of pre-defined rules and guidelines) provides a foundation for building applications, while a library (a collection of pre-written code snippets) offers specific functionalities that can be integrated into an application.

Next.js is a framework that provides a structure and features that simplify React development, unlike React, which is a library for building user interfaces.

Next.js MongoDB CRUD Example

Now, let's dive into the implementation of a Next.js MongoDB CRUD example.

Setting Up MongoDB Connection

First, we need to set up a connection to MongoDB in our Next.js application. We can use the mongodb package to interact with the database.

// pages/api/db.js

import { MongoClient } from 'mongodb';

export async function connectToDatabase() {
  const client = await MongoClient.connect(process.env.MONGODB_URI);
  return client.db(process.env.MONGODB_DB);
}
Enter fullscreen mode Exit fullscreen mode

Creating a New Record (Create)

Let's create an API route to add a new record to our MongoDB database.

// pages/api/createRecord.js

import { connectToDatabase } from './db';

export default async function handler(req, res) {
  const { name, age } = req.body;

  const db = await connectToDatabase();
  const records = db.collection('records');

  const result = await records.insertOne({ name, age });

  res.status(201).json(result.ops[0]);
}
Enter fullscreen mode Exit fullscreen mode

Fetching Records (Read)

We can create another API route to fetch all records from the database.

// pages/api/getAllRecords.js

import { connectToDatabase } from './db';

export default async function handler(req, res) {
  const db = await connectToDatabase();
  const records = db.collection('records');

  const result = await records.find({}).toArray();

  res.status(200).json(result);
}
Enter fullscreen mode Exit fullscreen mode

Updating a Record (Update)

Let's implement an API route to update an existing record in the database.

// pages/api/updateRecord.js

import { connectToDatabase } from './db';

export default async function handler(req, res) {
  const { id, name, age } = req.body;

  const db = await connectToDatabase();
  const records = db.collection('records');

  const result = await records.updateOne({ _id: ObjectId(id) }, { $set: { name, age } });

  res.status(200).json(result.ops[0]);
}
Enter fullscreen mode Exit fullscreen mode

Deleting a Record (Delete)

Lastly, we can create an API route to delete a record from the database based on its ID.

// pages/api/deleteRecord.js

import { connectToDatabase } from './db';

export default async function handler(req, res) {
  const { id } = req.body;

  const db = await connectToDatabase();
  const records = db.collection('records');

  const result = await records.deleteOne({ _id: ObjectId(id) });

  res.status(200).json({ message: 'Record deleted successfully' });
}
Enter fullscreen mode Exit fullscreen mode

FAQs

Q: Why is MongoDB used in this example?
A: MongoDB is a popular NoSQL database that provides flexibility and scalability, making it suitable for CRUD applications.

Q: What are API routes in Next.js?
A: API routes in Next.js allow us to create server-side functionality without the need for an external server setup.

Important to Know

It's essential to handle errors and validations properly in each CRUD operation to ensure data consistency and security.

By following this Next.js MongoDB CRUD example, you can build robust applications with efficient data management capabilities.


In this article, we covered a comprehensive Next.js MongoDB CRUD example with detailed explanations and code snippets. By leveraging Next.js and MongoDB together, you can create powerful and dynamic web applications seamlessly. Happy coding!

Top comments (0)