S42-Core MongoDB
MONGODB
Overview
The MongoClient
class/module in s42-core
provides an interface for interacting with MongoDB databases. It offers methods to connect to the database, retrieve collections, and perform operations on the data.
Recommended Usage
It is recommended to always call the getInstance
method to get an instance of MongoClient
instead of creating a new instance with the new
operator. This ensures that there is a single instance managing the MongoDB connection, which is more efficient and reliable.
Methods
connect()
Establishes a connection to the MongoDB database. This method should be called before performing any database operations.
ObjectId(id: string)
Converts a string to an ObjectId
, which is used as a unique identifier for documents in MongoDB.
- id: The string to convert to an
ObjectId
.
close()
Closes the MongoDB connection. This method should be called when the application is shutting down to ensure that all resources are properly released.
getDB()
Returns the database instance that was connected. This can be used to perform database operations directly.
getCollection(colName: string)
Retrieves a collection from the database.
- colName: The name of the collection to retrieve.
getInstance({ connectionString: string, database: string })
Returns the singleton instance of MongoClient
. If an instance does not already exist, it creates a new one.
- connectionString: The connection string for the MongoDB database.
- database: The name of the database to connect to.
Properties
mongoClient
The native MongoDB client instance.
db
The database instance that was connected.
databaseName
The name of the database.
instance
The singleton instance of MongoClient
.
Examples
Example 1: Connecting to MongoDB and Storing the Instance in Dependencies
In this example, we demonstrate how to connect to a MongoDB database using the MongoClient
class and store the instance in the application’s dependencies. This setup ensures that the MongoDB instance is easily accessible throughout the application.
Example 2: Accessing the MongoDB Instance from a Controller to Insert a User
In this example, we show how to access the MongoDB instance from a controller to perform an operation, such as inserting a new user into a collection. This demonstrates the practical use of the MongoClient
instance within different parts of the application.
Additional Details
The MongoClient
class in s42-core
simplifies the process of connecting to and interacting with MongoDB databases. By using the singleton pattern through the getInstance
method, it ensures that there is only one active connection to the database at any time, which helps manage resources more efficiently.