Skip to main content
100%

MongoDb singleton connection in NodeJs

✓ Published0🌍 Public
Aackuser
Last edited Apr 5, 2013
Created on Nov 24, 2016

This example shows a singleton pattern for a MongoDB connection in Node.js, ensuring only one database connection is reused across the application. The code uses the `mongodb` library’s `Db`, `Connection`, and `Server` constructors to create a connection to a local database at `127.0.0.1` with `auto_reconnect` enabled. A module-level `connectionInstance` variable caches the open connection; on each call, the exported function either returns the cached instance via a callback or opens a new one if none exists. The approach avoids repeated connection overhead by relying on the `db.open` method.

AI-generated description

Similar vizzes