1. Install the MongoDB driver for Node.js: npm install mongodb
1.1. Create a MongoDB cluster and obtain the connection URI.
1.2. Create a .env.local file in the root directory of your Next.js project.
1.3. Add the following line to the .env.local file, replacing with your actual MongoDB connection URI:
MONGODB_URI=<your-connection-uri>
2. Create a MongoDB utility file:
2.1 Create a new file called mongodb.js in the utils folder of your project.
2.2 Add the following code to establish a connection with the MongoDB database:
import { MongoClient } from 'mongodb';
let cachedClient = null;
export async function connectToDatabase() {
if (cachedClient && cachedClient.isConnected()) {
return cachedClient;
}
const client = await MongoClient.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
cachedClient = client;
return client;
}
1. Install the MongoDB driver for Node.js: npm install mongodb
1.1. Create a MongoDB cluster and obtain the connection URI. 1.2. Create a .env.local file in the root directory of your Next.js project. 1.3. Add the following line to the .env.local file, replacing with your actual MongoDB connection URI:
2. Create a MongoDB utility file:
2.1 Create a new file called mongodb.js in the utils folder of your project. 2.2 Add the following code to establish a connection with the MongoDB database: