2024-09-09 web, development, javascript

Read and Write To MongoDB

By O. Wolfson

This article provides a basic example of how to connect to a MongoDB database from a Next.js application and perform read and write operations on a specific document in a collection. This project provides a starting point for building more complex applications that use MongoDB for data storage and retrieval in a Next.js environment.

The code for this project is available on GitHub.

MongoDB Atlas is a fully-managed cloud-based database service that provides an easy and secure way to host, manage, and scale MongoDB databases on the cloud. MongoDB atlas provides a free tier that allows you more than enough bandwidth to get started with this project.

Step 1: Create a MongoDB Atlas account and cluster

  • Go to https://www.mongodb.com/cloud/atlas and create an account or log in
  • Create a new project and cluster
  • Add a new user with read and write access to the cluster
  • Whitelist your IP address in the network access tab

Step 2: Set up environment variables

  • Create a .env file in your Next.js application's root directory
  • Add the following variables with your own values:
    • MONGODB_URI=your-mongodb-uri
    • MONGODB_DB=your-mongodb-database-name
    • MONGODB_COLLECTION=your-mongodb-collection-name
  • If you are using version control, don't forget to add the .env file to your .gitignore file so that your credentials are not exposed in your repository.

The MongoDB URI is the connection string that you use to connect to your MongoDB cluster. It is made up of the following parts:

bash
mongodb+srv://<username>:<password>@<cluster-address>/<database-name>?retryWrites=true&w=majority

Step 3: Install required packages

  • Install the mongodb package: npm install mongodb

Step 4: Create API endpoints

  • Create a get-mongo-doc.ts file to define an API endpoint that retrieves a document from the collection by its _id field
  • Create an update-mongo-doc.ts file to define an API endpoint that updates a specific document in the collection

get-mongo-doc.ts

ts
import type { NextApiRequest, NextApiResponse } from "next";
import { MongoClient, ObjectId } from "mongodb";
import dotenv from "dotenv";

dotenv.config();
const { MONGODB_URI } = process.env;

type Data = {
  doc: any;
};

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  const client = await MongoClient.connect(MONGODB_URI!);
  const db = client.db(process.env.MONGODB_DB!);
  const collection = db.collection(process.env.MONGODB_COLLECTION!);
  const documentId = // <yourDocumentId>
  const doc = await collection.findOne({ _id: new ObjectId(documentId) });
  client.close();
  res.status(200).json({ doc });
}

update-mongo-doc.ts

ts
import type { NextApiRequest, NextApiResponse } from "next";
import { MongoClient, ObjectId } from "mongodb";
import dotenv from "dotenv";

dotenv.config();
const { MONGODB_URI } = process.env;

type Data = {
  doc: any;
};

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  const client = await MongoClient.connect(MONGODB_URI!);
  const db = client.db(process.env.MONGODB_DB!);
  const collection = db.collection(process.env.MONGODB_COLLECTION!);
  const documentId = // <yourDocumentId>
  const currentDate = new Date().toISOString();
  console.log("current date", currentDate);
  const updatedDoc = await collection.findOneAndUpdate(
    { _id: new ObjectId(documentId) },
    { $set: { title: "My Doc", content: currentDate } },
    { returnDocument: "after" }
  );
  client.close();
  res.status(200).json({ doc: updatedDoc });
}

Step 5: Create a React component

  • Create a Home.tsx file to define a React component that displays a button to get the document and a button to update the document
  • Define event handlers for the buttons that use the fetch() function to call the API endpoints and update the component's state with the response data

Event handlers:

tsx
// This is the function that gets the document
const handleGetMongoDoc = () => {
  console.log("get mongo doc");
  fetch("/api/get-mongo-doc") // This is the route we created in the previous step
    .then((response) => response.json())
    .then((data) => {
      const date = new Date(data.doc.content);
      console.log("Date:", date.toLocaleString());
      setData(date.toLocaleString());
    });
};

// This is the function that updates the document
const handleUpdateMongoDoc = () => {
  console.log("update mongo doc");
  fetch("/api/update-mongo-doc")
    .then((response) => response.json())
    .then((data) => {
      const date = new Date(data.doc.value.content);
      console.log("Date: ", date.toLocaleString());
      setData(date.toLocaleString());
    });
};

Step 6: Test the application

  • Start the Next.js development server: npm run dev
  • Open the application in a web browser and click the buttons to test the get and update operations

That's it. This tutorial provides a basic example of how to connect to a MongoDB database from a Next.js application and perform read and write operations on a specific document in a collection. You can expand on this example to build more complex applications that use MongoDB for data storage and retrieval.