Setup mongo
Unanswered
Eric Burel posted this in #help-forum
Hi, it's been a while since I set up Mongo in a new app and I've discovered than since 4.7, "new MongoClient" will auto-connect whenever actual data are being fetched, like calling ".db()" or "find().
So, it it right that deduplicating client could be as simple as the code below?
There would be one client per instance of this module, leading to an optimal amount of connection, but do I miss something here?
The example I find in the wild are much more convoluted and closer to what I would have done in the past, but that's because they try to manage the connection explicitely (call
So, it it right that deduplicating client could be as simple as the code below?
// in "lib/db.ts", that I can import from anywhere
export const client = new MongoClient(
serverConfig.mongodbUri
)
export const db = client.db(serverConfig.mongodbDb)There would be one client per instance of this module, leading to an optimal amount of connection, but do I miss something here?
The example I find in the wild are much more convoluted and closer to what I would have done in the past, but that's because they try to manage the connection explicitely (call
connect() and wait for it to finish, or use mongoose), which seems unnecessary nowadays