How to connect to MongoDB using Nextjs getStaticProps?

I found this article here:

Looking at the last example connecting with Static Geeration with MongoDB

Could anybody provide a sample code for the

import { connectToDatabase } from “…/util/mongodb”;

^^^ the …util/mongodb code is not shown in the article.

From there I can go to the rest of it like this and start working with the data.

export async function getStaticProps() {
10 const { db } = await connectToDatabase();
11
12 const movies = await db
13 .collection(“movies”)
14 .find({})
15 .sort({ metacritic: -1 })
16 .limit(1000)
17 .toArray();
18
19 return {
20 props: {
21 movies: JSON.parse(JSON.stringify(movies)),
22 },
23 };
24 }

1 Like

Hey @Edgar_Lindo. The code is located in this github repo.

I have also pasted it below:

import { MongoClient } from 'mongodb'

let uri = process.env.MONGODB_URI
let dbName = process.env.MONGODB_DB

let cachedClient = null
let cachedDb = null

if (!uri) {
  throw new Error(
    'Please define the MONGODB_URI environment variable inside .env.local'
  )
}

if (!dbName) {
  throw new Error(
    'Please define the MONGODB_DB environment variable inside .env.local'
  )
}

export async function connectToDatabase() {
  if (cachedClient && cachedDb) {
    return { client: cachedClient, db: cachedDb }
  }

  const client = await MongoClient.connect(uri, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })

  const db = await client.db(dbName)

  cachedClient = client
  cachedDb = db

  return { client, db }
}

Cheers!

My only head scratcher was on how to return props from the getStaticProps().
I lost 2 days until I saw the JSON.parse(JSON.stringify(dbData)) solution.
Does anyone know why can’t I return an array of objects?