Connecting to MongoDB Atlas

Hello! I am learning how to integrate MongoDB with NextJS and I can’t seem to connect to MongoDB when I render another page. Mongo connects on my index but not on my other pages.

I followed the tutorial in the docs…the only thing that is different is that the catch section which I found out requires a return statement.

No connection:

Hi @Christopher_Moua,

Welcome to the MongoDB Community forums :sparkles:

I suspect you might not be importing the MongoDB connection function to another page. Also, it seems that you’re using server-side props to determine the connection state. Note that using server-side props is not the right way to do this.

I’ll suggest, you create one db.js file and write the code to connect to MongoDB, sharing the code snippet for your reference:

import { MongoClient } from 'mongodb'

const uri = process.env.MONGODB_URI
const options = {
  useUnifiedTopology: true,
  useNewUrlParser: true,
}

const client = new MongoClient(uri, options)

export async function connectToDatabase() {
  await client.connect()
  return client.db(process.env.MONGODB_DB)
}

And then import it to other pages to do the database call and connect to the db. I’m sharing the code snippet for reference:

import App from 'next/app'
import { connectToDatabase } from '../db' // call db function to your another page

class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {
    const db = await connectToDatabase()
    const appProps = Component.getInitialProps
      ? await Component.getInitialProps(ctx)
      : {}

    return { ...appProps, db }
  }

In this way, it will work as expected.

Can you share the link to the documentation you followed? Meanwhile, you can check this tutorial on How to Integrate MongoDB Into Your Next.js App.

I hope it helps!

Thanks,
Kushagra