Skip to content

Commit 9eae155

Browse files
committed
fix: changes empty result query to be $expr with object, otherwise mongoose throws error
But mongo works OK with `{ $expr: false }` however official docs says it should be an object
1 parent 572b0e6 commit 9eae155

File tree

3 files changed

+6
-5
lines changed

3 files changed

+6
-5
lines changed

packages/casl-mongoose/spec/accessibleBy.spec.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ describe('accessibleBy', () => {
1616

1717
const query = accessibleBy(ability, 'update').Post
1818

19-
expect(query).toEqual({ $expr: false })
19+
expect(query).toEqual({ $expr: { $eq: [0, 1] } })
2020
})
2121

2222
it('returns `{ $expr: false }` if there is a rule that forbids previous one', () => {
@@ -27,7 +27,7 @@ describe('accessibleBy', () => {
2727

2828
const query = accessibleBy(ability, 'update').Post
2929

30-
expect(query).toEqual({ $expr: false })
30+
expect(query).toEqual({ $expr: { $eq: [0, 1] } })
3131
})
3232

3333
describe('it behaves like `toMongoQuery` when converting rules', () => {

packages/casl-mongoose/src/accessible_records.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
import { Normalize, AnyMongoAbility, Generics, ForbiddenError } from '@casl/ability';
22
import { Schema, QueryWithHelpers, Model, Document, HydratedDocument, Query } from 'mongoose';
3-
import { toMongoQuery } from './mongo';
3+
import { EMPTY_RESULT_QUERY, toMongoQuery } from './mongo';
44

55
function failedQuery(
66
ability: AnyMongoAbility,
77
action: string,
88
modelName: string,
99
query: QueryWithHelpers<Document, Document>
1010
) {
11-
query.where({ $expr: false }); // rule that returns empty result set
11+
query.where(EMPTY_RESULT_QUERY);
1212
const anyQuery: any = query;
1313

1414
if (typeof anyQuery.pre === 'function') {

packages/casl-mongoose/src/mongo.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,10 @@ export function accessibleBy<T extends AnyMongoAbility>(
3737
}, accessibleByProxyHandlers) as unknown as Record<StringOrKeysOf<RecordTypes>, AbilityQuery>;
3838
}
3939

40+
export const EMPTY_RESULT_QUERY = { $expr: { $eq: [0, 1] } };
4041
const accessibleByProxyHandlers: ProxyHandler<{ _ability: AnyMongoAbility, _action: string }> = {
4142
get(target, subjectType) {
4243
const query = rulesToQuery(target._ability, target._action, subjectType, convertToMongoQuery);
43-
return query === null ? { $expr: false } : query;
44+
return query === null ? EMPTY_RESULT_QUERY : query;
4445
}
4546
};

0 commit comments

Comments
 (0)