@cerbos/orm-mongoose
v2.1.0
Published
An adapter library that takes a [Cerbos](https://cerbos.dev) Query Plan ([PlanResources API](https://docs.cerbos.dev/cerbos/latest/api/index.html#resources-query-plan)) response and converts it into a [Mongoose](https://mongoosejs.com/) filter. It is desi
Downloads
457
Readme
Cerbos + Mongoose ORM Adapter
An adapter library that takes a Cerbos Query Plan (PlanResources API) response and converts it into a Mongoose filter. It is designed to run alongside a project that is already using the Cerbos JavaScript SDK to fetch query plans so that authorization logic can be pushed down to MongoDB.
How it works
- Use a Cerbos client (
@cerbos/httpor@cerbos/grpc) to callplanResourcesand obtain aPlanResourcesResponse. - Provide
queryPlanToMongoosewith that plan and an optional mapper that describes how Cerbos attribute paths relate to your document schema. - The adapter walks the Cerbos expression tree, translates supported operators to MongoDB syntax, and returns
{ kind, filters? }. - Inspect
result.kind:ALWAYS_ALLOWED: the caller can query without any additional filters.ALWAYS_DENIED: short-circuit and return an empty result set.CONDITIONAL: execute the query withresult.filters.
You can merge the adapter output with existing application filters (for example, via $and) before issuing the Mongoose query.
Supported operators
| Category | Operators | Behavior |
| --- | --- | --- |
| Logical | and, or, not | Builds $and, $or, and $nor groups. |
| Comparisons | eq, ne, lt, le, gt, ge | Emits $eq, $ne, $lt, $lte, $gt, $gte checks against the mapped field. |
| Membership | in, hasIntersection | $in on simple lists, or $elemMatch when targeting array relations; hasIntersection supports either a direct array field or a map projection inside the plan. |
| String helpers | contains, startsWith, endsWith | Generates escaped regular expressions that target substrings, prefixes, or suffixes. |
| Existence helpers | isSet, exists, exists_one | Uses $exists/$ne: null for scalars and $elemMatch for collections. |
| Collection helpers | filter, lambda, map, all | Translates Cerbos collection expressions into scoped $elemMatch filters and maps lambda variables to the correct nested paths. |
Any operator not listed above causes queryPlanToMongoose to throw Unsupported operator: <name>.
Note:
exists_onecurrently behaves like “at least one element matches”. Enforcing “exactly one” requires an aggregation pipeline, which is outside the scope of this adapter.
Requirements
- Cerbos > v0.16 plus either the
@cerbos/httpor@cerbos/grpcclient
System Requirements
- Node.js >= 20.0.0
- Mongoose 8.x
- A MongoDB-compatible server (MongoDB 5.0+ is recommended for compatibility with Mongoose 8)
Installation
npm install @cerbos/orm-mongooseAPI
import {
queryPlanToMongoose,
PlanKind,
type Mapper,
} from "@cerbos/orm-mongoose";
const result = queryPlanToMongoose({
queryPlan, // PlanResourcesResponse from Cerbos
mapper, // optional Mapper - see below
});
if (result.kind === PlanKind.CONDITIONAL) {
await MyModel.find(result.filters);
}PlanKind is re-exported from @cerbos/core:
export enum PlanKind {
ALWAYS_ALLOWED = "KIND_ALWAYS_ALLOWED",
ALWAYS_DENIED = "KIND_ALWAYS_DENIED",
CONDITIONAL = "KIND_CONDITIONAL",
}Mapper configuration
The Cerbos query plan references fields using paths such as request.resource.attr.title. Use a mapper to translate those names to the paths in your Mongoose models and to describe relations/collections so the adapter can generate $elemMatch filters when needed.
export type MapperConfig = {
field?: string;
valueParser?: (value: any) => any;
relation?: {
name: string;
type: "one" | "many";
field?: string;
fields?: Record<string, MapperConfig>;
};
};
export type Mapper =
| Record<string, MapperConfig>
| ((key: string) => MapperConfig);fieldrewrites a single Cerbos path to a different field in MongoDB.valueParsertransforms leaf values during filter construction. This is useful when the Cerbos plan contains string representations that need to be converted to MongoDB-specific types (for example, converting a string to anObjectId). The parser is applied to each value ineq,ne,lt,le,gt,ge, andinoperators. It also works on nested relation fields via thefieldsmap.relationdescribes embedded documents (type: "one") or arrays (type: "many"). Whenfieldis provided on a relation it identifies the property inside that relation that should be used for comparisons (for example, matchingcreatedBy.idwithout an$elemMatch).fieldssupplies nested overrides so lambda expressions such astag.namecan be mapped to the correct property.
If you omit the mapper the adapter will use the query plan paths verbatim, which only works when your Mongo documents follow the Cerbos naming convention.
Direct fields
const mapper: Mapper = {
"request.resource.attr.aBool": { field: "aBool" },
"request.resource.attr.aString": { field: "title" },
"request.principal.attr.department": { field: "principalDepartment" },
};Relations and collections
Use relation when mapping nested objects or arrays. type: "one" maps to embedded/single relations and results in dotted field paths, while type: "many" maps to arrays and lets the adapter emit $elemMatch conditions. The optional fields map lets you rename nested properties referenced in lambda expressions.
const mapper: Mapper = {
"request.resource.attr.createdBy": {
relation: {
name: "createdBy",
type: "one",
field: "id",
},
},
"request.resource.attr.tags": {
relation: {
name: "tags",
type: "many",
fields: {
id: { field: "id" },
name: { field: "name" },
},
},
},
};Collection operators in practice
Collection-aware operators (filter, exists, exists_one, hasIntersection, map, and all) require the mapper to declare the relation with type: "many". The adapter automatically scopes lambda variables and uses the fields map when translating expressions such as tag.name:
const mapper: Mapper = {
"request.resource.attr.tags": {
relation: {
name: "tags",
type: "many",
fields: {
name: { field: "name" },
},
},
},
};exists,exists_one, andfilterwrap the translated condition in$elemMatch.hasIntersectionworks for both scalar arrays and arrays of objects; when the plan usesmap(lambda(tag.name))the adapter projectstag.nametotags.$elemMatch.name.allconverts the lambda condition into a negated$elemMatchso that all elements must satisfy the predicate.- A bare
mapexpression verifies that the referenced nested path exists inside each element.
Mapper functions
You can also supply a function if your mappings follow a predictable pattern:
const mapper: Mapper = (path) => {
if (path.startsWith("request.resource.attr.")) {
return { field: path.replace("request.resource.attr.", "") };
}
if (path.startsWith("request.principal.attr.")) {
return { field: `principal.${path.replace("request.principal.attr.", "")}` };
}
return { field: path };
};Value parsing
Use valueParser to convert values from the Cerbos plan into types that MongoDB expects. A common use case is converting string IDs to ObjectId:
import { Types } from "mongoose";
const mapper: Mapper = {
"request.resource.attr.id": {
field: "_id",
valueParser: (value) => new Types.ObjectId(value),
},
};valueParser also works on nested relation fields via the fields map:
const mapper: Mapper = {
"request.resource.attr.createdBy": {
relation: {
name: "createdBy",
type: "one",
field: "id",
fields: {
id: {
field: "id",
valueParser: (value) => new Types.ObjectId(value),
},
},
},
},
};Usage example
import { GRPC as Cerbos } from "@cerbos/grpc";
import mongoose from "mongoose";
import {
queryPlanToMongoose,
PlanKind,
type Mapper,
} from "@cerbos/orm-mongoose";
await mongoose.connect("mongodb://127.0.0.1:27017/test");
const cerbos = new Cerbos("localhost:3592", { tls: false });
const MyModel = mongoose.model("MyModel", /* ... schema ... */);
const mapper: Mapper = {
"request.resource.attr.title": { field: "title" },
"request.resource.attr.owner": {
relation: { name: "owner", type: "one", field: "id" },
},
"request.resource.attr.tags": {
relation: {
name: "tags",
type: "many",
fields: { name: { field: "name" } },
},
},
};
const queryPlan = await cerbos.planResources({
principal: { id: "user1", roles: ["USER"] },
resource: { kind: "document" },
action: "view",
});
const result = queryPlanToMongoose({ queryPlan, mapper });
if (result.kind === PlanKind.ALWAYS_DENIED) {
return [];
}
const filters = result.kind === PlanKind.CONDITIONAL ? result.filters : {};
const records = await MyModel.find(filters);If you already have application-specific criteria you can combine them using $and:
const filters = result.kind === PlanKind.CONDITIONAL ? result.filters : {};
await MyModel.find({ $and: [filters ?? {}, { archived: false }] });Error handling
queryPlanToMongoose throws descriptive errors in the following scenarios:
- The plan kind is not one of the Cerbos
PlanKindvalues (Invalid query plan.). - A conditional plan omits the
operator/operandsstructure (Invalid Cerbos expression structure). - An operator listed in the plan is not implemented (
Unsupported operator: <name>). - Collection-oriented operators (
map,filter,exists,all, etc.) are used without arelationmapper, or with a mapper that declarestype: "one"wheretype: "many"is required (errors such asmap operator requires a relation mapping). - Lambda expressions in the plan are malformed (for example, missing a variable operand results in
Lambda variable must have a name). - Value operands do not match the expected type, e.g.,
hasIntersectionsupplies a non-array value.
Surfacing these errors early helps keep the adapter and your Cerbos policies in sync.
Limitations
exists_onebehaves like “at least one element matches” because counting matches requires an aggregation pipeline.- Operators not enumerated in Supported operators (such as search, mode, scalar math helpers, atomic number operations, composite keys, etc.) are not implemented and will throw
Unsupported operator. - All translations target standard MongoDB find filters; anything that would require
$expror a multi-stage aggregation pipeline is currently out of scope.
