Nextjs MongoDB template: clientPromise is not a function #33051
Answered
by
zneb
andytubeee
asked this question in
Help
|
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" Can someone give me a snippet of how to correctly use "clientPromise" object returned by the util script? |
Answered by
zneb
Jan 6, 2022
Replies: 1 comment 3 replies
|
Parentheses aren't needed. |
3 replies
Answer selected by
andytubeee
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Parentheses aren't needed.
clientPromise should be used like this:
const client = await clientPromise;const db = await client.db('optional db name');