tag-mongodb-api v1.1.0
Mongo DB API simplified
This is a wrapper above the Node.js MongoDB driver API. It's main goal is to reduce the complexity of handling connections and providing custom made and easy to use APIs to access the mongodb.
For full reference of the options refer to their documentation.
How to use
There are two ways of using this module:
- Managing the mongo connection
- The module manages the mongo connections
1. Managing the mongo connection
When you import the class MongodbApi
, the constructor expects a function that creates connections. With this approach, you have more flexibility and a bigger burden since you are the responsible to manage the connections.
const { MongodbApi } = require('@taglivros/tag-mongodb-api')
const connectToDatabase = () => {
// connection implementation
}
const mongodbApi = new MongodbApi( connectToDatabase )
2. The module manages the mongo connections
When you import the dbApi
the module looks for the following environment variable:
- MONGODB_SERVER_URI : Url to access the database with the credentials
- MONGODB_NAME : The name of the database to connect
Then it creates a connection, if it wasn't created yet, and returns the dbApi
which uses the connection. Once the connection is created, the module relies on a caching mechanism, to reuse connections.
API
aggregate
// TO DO
count
// TO DO
find
// TO DO
softDeleteOne
// TO DO
deleteOne
//TO DO
updateOne
//TO DO
updateOneById
//TO DO
createOrUpdateONe
//TO DO
findOne
Find one document in a collection.
Usage:
async ( id, email ) => {
const document = await dbApi.findOne( 'Collection', { _id: id, email }, { sort: { createdAt: -1 } } )
}
Returns the document or a NotFound
in case query don't match anything.
May also throw a DatabaseException
.
findOneById
Sintax sugar for findOne( { _id: id } )
Usage:
async () => {
const document = await dbApi.findOneById( 'Collection', 'id' )
}
Returns the document or a NotFound
in case id don't exist.
May also throw a DatabaseException
.
insertOne
Inserts a document to the collection
Usage:
async () => {
const document = await dbApi.insertOne( 'Collection', { name: 'UserName', age: 23 } )
}
Returns the document created.
May also throw a DatabaseException
.
Collaborating
- Create a pull request
- Merge after having 2 or more approves
3 years ago