-
Notifications
You must be signed in to change notification settings - Fork 34
Cache mongo client, not client promise #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Cache mongo client, not client promise #1
Conversation
await client.connect(); | ||
// `await client.connect()` will use the default database passed in the MONGODB_URI |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am not sure what it means for connect to "use a database" and the line below still references "clientPromise".
I would uncomment the sample find
code, just cutting to the chase so to speak.
|
||
if (process.env.NODE_ENV === "development") { | ||
// In development mode, use a global variable so that the value | ||
// is preserved across module reloads caused by HMR (Hot Module Replacement). | ||
let globalWithMongo = global as typeof globalThis & { | ||
_mongoClientPromise?: Promise<MongoClient>; | ||
_mongoClient?: MongoClient; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
types/mongodb.d.ts
still references the old global.
Optional, can we use globalThis
(instead of global
) here? Sticks out as legacy to me, but not necessary.
Thanks for this guys! Curious to know if you have a solution for people using prisma as ORM with the mongodb driver? |
Thanks applied the same solution. Will confirm how it goes after observing for a week or so |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I tested everything locally and it works. I did not have the 504 errors though, so I can't confirm that it solves that issue. It does not, however, introduce new errors.
This fix works very well. I have been observing vercel logs for the last 10 hrs for my app and not seeing 500 errors anymore. |
Hey @Rieranthony - Prisma doesn't actually use the Node driver (see prisma/prisma#12886). If you're seeing timeout errors from Prisma, I'd suggest reaching out to them, since they'll be better equipped to troubleshoot. |
I just updated my code because of the same pattern. Hopefully, this will fix the troublemaker! |
Caching the client's promise can lead to unhandled promise rejections if the client fails to connect. Caching the client avoids this pitfall.
The mongo client will auto connect on the first operation.