@merlin4/mongodb-connect
v0.0.2
Published
Utility functions to simplify connecting to a MongoDB database.
Downloads
3
Maintainers
Readme
mongodb-connect
Utility functions to simplify connecting to a MongoDB database.
Install
Install peer dependencies:
npm install config debug mongodb
Install this package:
npm install @merlin4/mongodb-connect
Configuration
This package uses config to load connection details. As such the following options are used:
- db.url - contains the connection string for the database
- db.name - contains the database name
- db.debug - specifies the debug channel that should be used
Shown below are some example config files.
config/default.json
{
"db": {
"url": "mongodb://localhost:27017",
"name": "test",
"debug": "app:database"
}
}
config/custom-environment-variables.json
{
"db": {
"url": "DB_URL",
"name": "DB_NAME",
"debug": "DB_DEBUG"
}
}
Usage
Import the utility functions:
const { connect, ping, newId } = require('@merlin4/mongodb-connect');
Test the connectivity:
Promise.resolve(ping())
.then(() => console.log('Connected to database.'))
.catch((err) => console.error(err));
Find all documents in a collection:
const db = await connect();
const products = await db.collection('products').find({}).toArray();
Generate a new ObjectId:
const id = newId();
Parse an ObjectId from a string:
const idString = '61608aa55318d3e1f8595804';
const id = newId(idString);