Next.js Discord

Discord Forum

Shall i connect once or on every mongodb query ?

Answered
Maine Coon posted this in #help-forum
Open in Discord
Maine CoonOP
Hi, i'm starting a Next project and want to use mongoDb in the server side.
i saw some tutorial/documentation where they connect on each db query.
Would it not be better to connect once (on root app) and use Schema to query the db ?

thanks !
Answered by linesofcode
let connection;
const getDb = async () => {
   if (connection) return connection
   connection = await connectToMongo()
   return connection 
}
View full answer

17 Replies

Connect once
but keep in mind that the mongo package you're using
might handle the deduping of multiple connections
under the hood
So even if you do multiple connections, it will still just be 1
something worth investigating
Maine CoonOP
ok, so best practices would be to connect once, but connecting everywhere SHALL not be a problem, right ?
it depends on the library
connecting everywhere can indeed be a problem because if there arent some defensive steps taken
then you could max out your connection count
let connection;
const getDb = async () => {
   if (connection) return connection
   connection = await connectToMongo()
   return connection 
}
Answer
this is how i would do it
(syntax may not be correct, this is just an example)
and this way you'll only connect once
just call getDb() whenever you need a reference to your connection
Maine CoonOP
cool idea ! thanks mate !
Original message was deleted
Giant panda
You have been warned twice already. This is your first strike and I have timed you out for now. If you continue this, we will ban you from the server.