Nextjs MongoDB template: clientPromise is not a function

Viewed 77

I am using Next.js's MongoDB example template and it comes with a MongoDB util function:

import { MongoClient } from 'mongodb';

const uri = process.env.MONGODB_URI;
const options = {};

let client;
let clientPromise;

if (!process.env.MONGODB_URI) {
  throw new Error('Please add your Mongo URI to .env.local');
}

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;

Here is how I am using it and I am certain that I am using this incorrectly.

import { clientPromise } from '../../lib/mongodb';

export default async (req, res) => {
  try {
    const db = await clientPromise();
    const users = await db.collection('users').find({}).limit(20).toArray();
    res.json(users);
  } catch (e) {
    console.error(e);
    res.json({ error: 'Not connected!' });
  }
};

The error is "TypeError: (0 , lib_mongodb__WEBPACK_IMPORTED_MODULE_0_.clientPromise) is not a function"

1 Answers

You're exporting clientPromise, which is client.connect(). At this point you already "triggered" the connection function. now all you have to do is wait on that promise,

So instead of

const db = await clientPromise();

You should do:

const connection = await clientPromise; // this is a client connection not a db
const db = connection.db();
Related