opticore-mongodb
v1.1.5
Published
opticore mongo driver data base
Readme
Installation
npm install opticore-mongodb
Summary
This package contains a database connection for mongodb (https://github.com/guyzoum77/opticore-mongodb).
Usage
import {MongoCore} from "opticore-mongodb";
const mongoConn: MongoCore = new MongoCore(connectionUri, localLang, options);
mongoConn.connection("dbName"");Details
- connectionUri: This is connection string, which tells the Node.js driver which MongoDB deployment to connect to.
- localLang: a default local language
- options: This is an interface that defines all the configuration parameters available to establish a connection between a Node.js application and MongoDB
Query Builder
QueryBuilder is a fluent, chainable API for building MongoDB find filters and
aggregation pipelines without writing raw MongoDB query objects by hand. It works
against any Db instance from the official mongodb driver.
import { MongoClient, Db } from "mongodb";
import { QueryBuilder } from "opticore-mongodb";
const client = await MongoClient.connect(connectionUri);
const db: Db = client.db("myDatabase");
const activeAdults = await new QueryBuilder("users")
.where("status", "active")
.where("age", "gte", 18)
.sort({ createdAt: -1 })
.limit(20)
.execute(db);Creating a builder
new QueryBuilder<T = Document>(collectionName: string, config?: QueryBuilderConfigInterface)- collectionName: name of the MongoDB collection to query.
- T: optional type of the documents returned by the collection.
- config (optional):
defaultLimit— limit applied when.limit()was never called (default:10).maxLimit— upper bound.limit()is clamped to (default:1000).validateFields— allow-list of field names; calling a field-based method (where,in,notIn,regex,greaterThan, ...) with a field outside this list throws anError.
Building filters
| Method | Description |
|---|---|
| .where(field, value) | Equality condition |
| .where(field, operator, value) | Condition with an explicit operator ("eq", "ne", "gt", "gte", "lt", "lte", "in", "nin", "exists", "type", "regex", "options") |
| .and(filter) | Adds a filter combined with $and |
| .or(conditions[]) | Sets the $or conditions |
| .in(field, values[]) | $in condition |
| .notIn(field, values[]) | $nin condition |
| .regex(field, pattern, options?) | $regex condition (accepts a string or a RegExp; reuses the RegExp's own flags when options is omitted) |
| .greaterThan(field, value) | $gt condition |
| .greaterThanOrEqual(field, value) | $gte condition |
| .lessThan(field, value) | $lt condition |
| .lessThanOrEqual(field, value) | $lte condition |
| .notEqual(field, value) | $ne condition |
| .exists(field, value?) | $exists condition (defaults to true) |
| .addCustomFilter(filter) | Merges a raw MongoDB filter object into the current filters |
Shaping results
| Method | Description |
|---|---|
| .limit(n) | Caps the number of returned documents (clamped to [0, maxLimit]) |
| .skip(n) | Skips the first n documents (clamped to >= 0) |
| .sort({ field: 1 \| -1 }) | Sets the sort order |
| .select({ field: 1 \| 0 }) | Sets the projection |
Running the query
| Method | Description |
|---|---|
| .execute(db) | Runs a find with the current filters/options, or the aggregation pipeline if .aggregate() was used. Returns Promise<T[]> |
| .count(db) | Counts documents matching the current filters. Returns Promise<number> |
| .documentExists(db) | Returns Promise<boolean> — whether at least one document matches |
| .findOne(db) | Returns Promise<T \| null> — the first matching document |
Aggregation pipelines
const results = await new QueryBuilder("orders")
.where("status", "paid")
.aggregate([
{ $group: { _id: "$customerId", total: { $sum: "$amount" } } }
])
.executeAggregation(db);.aggregate(stages[])— sets the pipeline (replaces any previous one)..addAggregationStage(stage)— appends a single stage to the pipeline..executeAggregation(db)— runs the pipeline, automatically prefixed with a$matchstage built from the current filters (if any) and suffixed with$sort/$skip/$limit/$projectstages built from.sort()/.skip()/.limit()/.select().- Calling
.execute(db)after.aggregate()behaves the same as.executeAggregation(db).
Utilities
.getFilters()/.getOptions()— return a copy of the current filters/options..resetFilters()/.resetOptions()/.reset()— clear filters, options, or everything (including the pipeline)..clone()— returns an independent copy of the builder..toJSON()— plain object snapshot of the builder's state (collection name, filters, options, pipeline)..debug()— logs the current state to the console and returnsthis, so it can be inserted anywhere in a chain.
Contributors
This package is led by Guy-serge Kouacou.
Contributing
This project welcomes contributions from the community. Contributions are accepted using GitHub pull requests. If you're not familiar with making GitHub pull requests, please refer to the GitHub documentation "Creating a pull request."
