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:
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
update-mongo-doc.ts
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:
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.