I am very new to MongoDB. I was following along with the Next js and MongoDB tutorial, making sure that my files were written correctly. However, I am stuck on trying to get a response. For some reason, my MongoDB cluster shows that there were some connections that were made upon refreshing the page, even though it never sends any data back.
I thought it might help to mention where all of these MongoDB connection setup pieces are located, just to be sure I set them up correctly.
Within my app folder, I have an api folder and a lib folder. Inside the api folder, I have test.js:
import clientPromise from "../lib/mongodb";
export default async (req, res) => {
try {
const client = await clientPromise;
const db = client.db("database_name");
const movies = await db
.collection("collection_name")
.find({})
.limit(10)
.toArray();
res.json(movies);
console.log(movies)
} catch (e) {
console.error(e);
}
};
Inside the lib folder, I have mongodb.js:
import { MongoClient } from 'mongodb'
if (!process.env.MONGODB_URI) {
throw new Error('Invalid/Missing environment variable: "MONGODB_URI"')
}
const uri = process.env.MONGODB_URI
const options = {}
let client
let clientPromise
if (process.env.NODE_ENV === 'development') {
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options)
global._mongoClientPromise = client.connect()
}
clientPromise = global._mongoClientPromise
} else {
client = new MongoClient(uri, options)
clientPromise = client.connect()
}
export default clientPromise
In my main page.jsx I’ve tested out clientPromise to see if it really works, but it says that isConnected is false:
export async function GetServerSideProps(context) {
try {
await clientPromise
console.log('success!')
return {
props: { isConnected: true },
}
} catch (e) {
console.error(e)
return {
props: { isConnected: false },
}
}
}
export default function Home({isConnected}) {
return (
<div>
{
isConnected
?
<h2>Success!</h2>
:
<h2>Failure!</h2>
}
</div>
)
}
outside my app folder, I have a types folder, which has mongodb.d.js:
import { MongoClient } from 'mongodb'
if (!process.env.MONGODB_URI) {
throw new Error('Invalid environment variable: "MONGODB_URI"')
}
const uri = process.env.MONGODB_URI
const options = {}
I am unsure how to move forward, as there seems to be no signs of life or data in the Next js-MongoDB connection.
If you would like me to explain certain things better, or if you have any suggestions for a possible solution, please let me know!
Thank you.