CodeBucks logo
WebNews
MongoDB

How to use MongoDB with Next.JS || Complete Guide

How to use MongoDB with Next.JS || Complete Guide
0 views
3 min read
#MongoDB
Table Of Content
Headings: 10 (H2: 10, H3: 0)

Hii Developer's I am Hiren ray and today i tech you How to use MongoDB on your next js Project. But First learn What is a mongoDb or how to Work it.

What is a MongoDB#

Mongo Db is a no Sql Database and It's fast or scalabel To Feture and it's Esay to use

How to Use MongoDb#

First If you want to use mongoDb SO first Install The packege if any code you first install the packege So this is Installation Procees

code
//common of use npm packege
npm i mongoose
//Rearly use 
yarn i mongoose

so understand this and Next

MongoDb use on Next.js Projext#

First install the Projext

code
npx create-next-app@latest my-next-mongo-app
cd my-next-mongo-app
npm run dev

Create A Free acoount on Mongodb Atlas#

Copy the Connextion string like this
// mongodb+srv://username:password@cluster.mongodb.net/mydb //
and Install The Packege ** npm i mongoose

Create .env File#

create the file file name (.env)
and use this

code
MONGODB_UR:=mongodb+srv://username:password@cluster.mongodb.net/mydb

Create a Connection file to Database lib/mongoose.js#

code
import { MongoClient } from "mongodb";

const uri = process.env.MONGODB_URI;
const options = {};

let client;
let clientPromise;

if (!process.env.MONGODB_URI) {
  throw new Error("Please add MONGODB_URI to .env.local");
}

client = new MongoClient(uri, options);
clientPromise = client.connect();

export default clientPromise;

Create A api route like this - api/post/route.js#

code
import clientPromise from "@/lib/mongodb";

export async function GET() {
  const client = await clientPromise;
  const db = client.db("mydb");

  const posts = await db.collection("posts").find({}).toArray();

  return Response.json(posts);
}

export async function POST(req) {
  const body = await req.json();
  const client = await clientPromise;
  const db = client.db("mydb");

  await db.collection("posts").insertOne(body);

  return Response.json({ success: true });
}

Fetch the data to Database#

code
async function getPosts() {
  const res = await fetch("http://localhost:3000/api/posts", {
    cache: "no-store",
  });
  return res.json();
}

export default async function Home() {
  const posts = await getPosts();

  return (
    <div>
      <h1>My Posts</h1>
      {posts.map((post) => (
        <div key={post._id}>
          <h3>{post.title}</h3>
          <p>{post.content}</p>
        </div>
      ))}
    </div>
  );
}

Send The data Frontend to Api#

code
"use client";

export default function AddPost() {
  async function handleSubmit(e) {
    e.preventDefault();

    await fetch("/api/posts", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        title: "My First Post",
        content: "MongoDB with Next.js is easy!",
      }),
    });

    alert("Post added");
  }

  return <button onClick={handleSubmit}>Add Post</button>;
}

Here Is the Folder Structure#

code
/app
  /api/posts/route.js
  /page.js
/lib
  mongodb.js
.env.local

Soo if you understand to using the blog and learn anything so share the blog