What is @ucast/mongo?
@ucast/mongo is a package that allows you to apply conditions and filters to MongoDB queries using a unified and flexible syntax. It is part of the UCAS (Universal Conditions and Specifications) library, which provides a way to define and evaluate conditions in a consistent manner across different platforms and databases.
What are @ucast/mongo's main functionalities?
Creating Conditions
This feature allows you to create complex conditions using MongoDB's query syntax. The example demonstrates how to create a condition that checks if the age is greater than 18 and the name matches a regex pattern.
const { createCondition } = require('@ucast/mongo');
const condition = createCondition({
$and: [
{ age: { $gt: 18 } },
{ name: { $regex: 'John' } }
]
});
console.log(condition);
Evaluating Conditions
This feature allows you to evaluate conditions against a given data object. The example shows how to evaluate if the age in the data object is greater than 18.
const { evaluateCondition } = require('@ucast/mongo');
const condition = { age: { $gt: 18 } };
const data = { age: 20 };
const result = evaluateCondition(condition, data);
console.log(result); // true
Combining Conditions
This feature allows you to combine multiple conditions using logical operators like $and, $or, etc. The example demonstrates how to combine two conditions using the $and operator.
const { combineConditions } = require('@ucast/mongo');
const condition1 = { age: { $gt: 18 } };
const condition2 = { name: { $regex: 'John' } };
const combinedCondition = combineConditions('$and', [condition1, condition2]);
console.log(combinedCondition);
Other packages similar to @ucast/mongo
mongoose
Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js. It provides a higher-level abstraction for interacting with MongoDB, including schema definitions, model validation, and query building. Unlike @ucast/mongo, which focuses on condition creation and evaluation, Mongoose offers a full suite of tools for working with MongoDB in a more structured way.
mongodb
The official MongoDB driver for Node.js provides a low-level API for interacting with MongoDB databases. It allows you to perform CRUD operations, manage indexes, and run aggregation pipelines. While it offers more control and flexibility, it lacks the higher-level condition creation and evaluation features provided by @ucast/mongo.
json-rules-engine
json-rules-engine is a powerful, lightweight rules engine for Node.js. It allows you to define and evaluate complex business rules in JSON format. While it is not specific to MongoDB, it offers similar functionality in terms of condition evaluation and can be used in a broader range of applications.
UCAST Mongo
This package is a part of ucast ecosystem. It provides a parser that can parse MongoDB query into conditions AST.
Installation
npm i @ucast/mongo
yarn add @ucast/mongo
pnpm add @ucast/mongo
Getting Started
To parse MongoDB query into conditions AST, you need to create a MongoQueryParser
instance:
import { MongoQueryParser, allParsingInstructions } from '@ucast/mongo';
const parser = new MongoQueryParser(allParsingInstructions);
const ast = parser.parse({
id: 1,
active: true
});
To create a parser you need to pass in it parsing instruction. Parsing instruction is an object that defines how a particular operator should be parsed. There are 3 types of ParsingInstruction
, one for each Condition
:
FieldInstruction
It represents an instruction for an operator which operates in a field context only. For example, operators $eq
, $lt
, $not
, $regex
CompoundInstruction
It represents an instruction for an operator which operates in a document context and contains nested queries. For example, operators $and
, $or
, $nor
ValueInstruction
It represents an instruction for an operator which operates in a document context only. For example, $where
Optimization logic
It's important to understand that it's not required for FieldInstruction
to be parsed into FieldCondition
. I can be parsed into CompoundCondition
as it's done for $not
operator.
Also some operators like $and
and $or
optimize their parsing logic, so if one of that operators contain only one condition it will be resolved to FieldCondition
.
As said before $and
and $or
operators optimize their representation in case they have a single condition but this is not all. They also recursively collapse conditions from nested operators with the same name. Let's see an example to understand what this means:
const ast = parser.parse({
a: 1
$and: [
{ b: 2 },
{ c: 3 }
]
});
console.dir(ast, { depth: null })
This optimization logic helps to speed up interpreter's execution time, instead of going deeply over tree-like structure we have a plain structure of all conditions under a single compound condition.
Pay attention: parser removes $
prefix from operator names, so the resulting AST operators doesn't have in its operator
property!
Custom Operator
In order for an operator to be parsed, it needs to define a parsing instruction. Let's implement a custom instruction which checks that object corresponds to a particular json schema.
First of all, we need to understand on which level this operator operates (field or document). In this case, $jsonSchema
clearly operates on document level. It doesn't contain nested MongoDB queries, so it should be defined using DocumentInstruction
.
To test that document corresponds to provided json schema, we will use ajv but it's possible to use any JSON schema validator you want.
import { DocumentInstruction, DocumentCondition } from '@ucast/core';
import Ajv from 'ajv';
export const $jsonSchema: DocumentInstruction = {
type: 'document',
validate(instruction, value) {
if (!value || typeof value !== 'object') {
throw new Error(`"${instruction.name}" expects to receive an object`)
}
},
parse(instruction, schema) {
const ajv = new Ajv();
return new DocumentCondition(instruction.name, ajv.compile(schema));
}
};
In order to use this operator, we need to pass it into MongoQueryParser
constructor:
import { MongoQueryParser, allParsingInstructions } from '@ucast/core';
import { $jsonSchema } from './operators/jsonSchema';
const parser = new MongoQueryParser({ ...allParsingInstructions, $jsonSchema });
const ast = parser.parse({
$jsonSchema: {
type: 'object',
properties: {
firstName: { type: 'string' },
lastName: { type: 'string' },
},
additionalProperties: false,
}
});
console.dir(ast, { depth: null });
The only thing which is left is to implement a corresponding interpreter.
Want to help?
Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on guidelines for contributing
License
Apache License, Version 2.0