mongodb-connection-nodejs
v1.0.1
Published
A simple and universal MongoDB connection utility for Node.js that works with both CommonJS and ES modules
Maintainers
Readme
mongodb-connection-nodejs
A simple and universal MongoDB connection utility for Node.js that works with both CommonJS and ES modules.
Installation
npm install mongodb-connection-nodejsFeatures
- 🚀 Simple and lightweight MongoDB connection utility
- 🔄 Works with both CommonJS and ES modules
- 🛡️ Built on top of Mongoose
- ⚡ Connection reuse to prevent multiple connections
- 🎯 TypeScript friendly
Usage
ES Modules (import)
import { connect } from 'mongodb-connection-nodejs';
async function main() {
try {
const connection = await connect('mongodb://localhost:27017/mydb');
console.log('Connected to MongoDB!');
// Your database operations here
} catch (error) {
console.error('Connection failed:', error);
}
}
main();CommonJS (require)
const { connect } = require('mongodb-connection-nodejs');
async function main() {
try {
const connection = await connect('mongodb://localhost:27017/mydb');
console.log('Connected to MongoDB!');
// Your database operations here
} catch (error) {
console.error('Connection failed:', error);
}
}
main();With Options
import { connect } from 'mongodb-connection-nodejs';
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
maxPoolSize: 10,
serverSelectionTimeoutMS: 5000,
};
const connection = await connect('mongodb://localhost:27017/mydb', options);API
connect(uri, options?)
Connects to MongoDB using the provided URI and options.
Parameters
uri(string): MongoDB connection stringoptions(object, optional): Mongoose connection options
Returns
Promise<mongoose.Connection>: The mongoose connection instance
Example
const connection = await connect('mongodb://localhost:27017/mydb');Connection Reuse
The utility automatically reuses existing connections, so you can call connect() multiple times without creating duplicate connections.
Requirements
- Node.js >= 14.0.0
- MongoDB server
Dependencies
- mongoose: ^8.17.1
License
MIT
Author
sarvesh.dev
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
