A powerful and customizable query builder for Mongoose, simplifying complex aggregation and query construction with support for search, filter, sort, pagination, population and aggregation.
To install qgenie, run the following command in your project directory:
npm install qgenie
Here's a basic example of how to use qgenie in your project:
import { QueryBuilder } from "qgenie";
import { YourMongooseModel } from "./your-model";
async function getItems(queryString: Record) {
const query = YourMongooseModel.find();
const queryBuilder = new QueryBuilder(query, queryString);
const result = await queryBuilder
.search(["name", "description", "industry.name"])
.filter()
.sort()
.paginate()
.populate("category")
.executeWithMetadata();
return result;
}
Search across multiple or nested fields:
queryBuilder.search(["name", "description"]);
// combine nested fields:
queryBuilder.search(["name", "description", "nested.field"]);
Apply filters based on query parameters:
queryBuilder.filter();
Supports operators like `gt`, `gte`, `lt`, `lte`, and `in`.
Sort results:
queryBuilder.sort("-createdAt");
Paginate results:
queryBuilder.paginate(10); // 10 items per page
Populate related fields:
queryBuilder.populate("category");
// or
queryBuilder.populate(["category", "author"]);
// or
queryBuilder.populate([{ path: "category", select: "name" }]);
// or
queryBuilder.populate([{ path: "category", select: ["name", "status"] }]);
// or
queryBuilder.populate([
{ path: "category", select: ["name", "status"] },
{ path: "user" },
]);
Execute the query:
const data = await queryBuilder.exec();
Execute the query and get metadata:
const { meta, data } = await queryBuilder.executeWithMetadata();
Perform aggregation using qgenie:
const aggregationPipeline = [
{ $match: { status: "active" } },
{ $group: { _id: "$category", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } },
];
const aggregatedResult = await queryBuilder.aggregate(aggregationPipeline);
Here's an example of a complex query string that demonstrates various features of qgenie:
?search=smartphone&category=electronics&price[gte]=500&price[lte]=1000&inStock=true&sort=-price,name&page=2&limit=20&populate=manufacturer
This query string does the following:
Here's how you would use this query string with qgenie:
import { QueryBuilder } from "qgenie";
import { Product } from "./your-product-model";
async function getProducts(queryString: Record) {
const query = Product.find();
const queryBuilder = new QueryBuilder(query, queryString);
const result = await queryBuilder
.search(["name", "description"])
.filter()
.sort()
.paginate()
.populate("manufacturer")
.executeWithMetadata();
return result;
}
// Usage
const queryString = {
search: "smartphone",
category: "electronics",
"price[gte]": "500",
"price[lte]": "1000",
inStock: "true",
sort: "-price,name",
page: "2",
limit: "20",
populate: "manufacturer",
};
const products = await getProducts(queryString);
console.log(products);
Here's an example demonstrating how to use the aggregation feature:
import { QueryBuilder } from "qgenie";
import { Order } from "./your-order-model";
async function getSalesData() {
const query = Order.find();
const queryBuilder = new QueryBuilder(query, {});
const aggregationPipeline = [
{ $match: { status: "completed" } },
{ $group: { _id: "$region", totalSales: { $sum: "$amount" } } },
{ $sort: { totalSales: -1 } },
];
const aggregatedResult = await queryBuilder.aggregate(aggregationPipeline);
return aggregatedResult;
}
// Usage
const salesData = await getSalesData();
console.log(salesData);
This example aggregates sales data by region, calculating the total sales amount for each region and sorting the results in descending order of total sales.
constructor(modelQuery: ReturnType<Model<T>["find"]>, queryString: Record<string, any>)
search(fields: (keyof T)[]): this
filter(): this
sort(defaultSort: string): this
paginate(defaultLimit: number): this
populate(fields: string | string[] | Record<string, any>[]): this
aggregate(pipeline: Record<string, any>[]): Promise<any[]>
async exec(): Promise<T[]>
async executeWithMetadata(): Promise<{ meta: { total: number, page: number, limit: number, totalPages: number }, data: T[] }>