Mongodb cluster shows recent activity, but my website doesn't respond with any data

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.

Hey @Mira_Kershisnik,

Welcome to the MongoDB Community :sparkles:

Could you please refer to this GitHub repository: nextjs-with-mongodb and ensure that you have all the code set up correctly with the right file names? Also, make sure you are passing the correct MongoDB srv connection string in your .env file.

Give it a try, and feel free to reach out in case you encounter any further errors, providing the error stack and the workflow you tried. This will help others understand the issue better and assist you effectively.

Best regards,
Kushagra

Hey @Mira_Kershisnik,

One additional thing is to make sure that you have allowed your IP address in the Network Access tab to ensure it is allowed to connect to the database.

~ Kushagra

Hello! I have managed to fix the errors by watching these three videos

I was using JavaScript, and I tried my best to figure out how a JavaScript version would work using the TypeScript example. However, I think that was where I got stuck, and then found the first video. The first video explains how to connect NextJS to MongoDB. In the the mongodb.js file I made sure to mention the database and the collection I was getting the data from.

The second video explains how to connect NextJS with Express, and it helped me move everything server-related to its own folder. This helped separate the backend from the frontend. I imported the dotenv npm package, and kept the .env file in the directory that will be running the server.

The third video explains how to add Mongoose schemas to the mix, because I thought Mongoose would be super helpful to work with, and it was!

The file names turned out to be all correct, there was just something that I couldn’t quite translate over to JavaScript from the example. I have the correct MONGODB_URI written down in my .env file, and my IP address is allowed to connect to the database.

It was a good learning experience, and I truly appreciate all the suggestions you provided for me! Thank you, Kushagra!

Best,

Snowy

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.