Skip to content

Commit

Permalink
fix($filter): Properly handle truthy values. Closes #320
Browse files Browse the repository at this point in the history
  • Loading branch information
kofrasa committed Mar 28, 2023
1 parent 8ba5ea7 commit 7c59005
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 24 deletions.
3 changes: 2 additions & 1 deletion src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,8 @@ export interface Options {
/**
* Enforces strict MongoDB compatibilty. See readme for differences. @default true.
* When disabled, the following behaviours take effect.
* - $elemMatch projection operator returns all matching nested documents instead of only the first.
* * $elemMatch projection operator returns all matching nested documents instead of only the first.
* * $filter expression treats empty string "" as falsey consistent with Javascript.
*/
readonly useStrictMode?: boolean;
/**
Expand Down
31 changes: 17 additions & 14 deletions src/operators/expression/array/filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import { assert, isArray } from "../../../util";
/**
* Selects a subset of the array to return an array with only the elements that match the filter condition.
*
* @param {Object} obj [description]
* @param {*} expr [description]
* @return {*} [description]
* @param {Object} obj The current document
* @param {*} expr The filter spec
* @return {*}
*/
export function $filter(
obj: RawObject,
Expand All @@ -21,15 +21,18 @@ export function $filter(

const copts = ComputeOptions.init(options, obj);
const k = expr.as || "this";
return input.filter(
(o: AnyVal) =>
computeValue(
obj,
expr.cond,
null,
copts.update(copts.root, {
variables: { [k]: o },
})
) === true
);
const local = {
variables: { [k]: null },
};
return input.filter((o: AnyVal) => {
local.variables[k] = o;
const b = computeValue(
obj,
expr.cond,
null,
copts.update(copts.root, local)
);
// allow empty strings only in strict MongoDB mode (default).
return !!b || (b === "" && options.useStrictMode);
});
}
26 changes: 17 additions & 9 deletions test/operators/expression/array/filter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,24 @@ support.runTest(support.testPath(__filename), {
$filter: [
[
{
input: [1, "a", 2, null, 3.1, 4, "5"],
as: "num",
cond: {
$and: [
{ $gte: ["$$num", Number.MIN_SAFE_INTEGER] },
{ $lte: ["$$num", Number.MAX_SAFE_INTEGER] },
],
},
input: [
"string",
"",
1,
0,
1.5,
NaN,
undefined,
null,
true,
false,
[],
{},
],
as: "item",
cond: "$$item",
},
[1, 2, 3.1, 4],
["string", "", 1, 1.5, true, [], {}],
],
],
});

0 comments on commit 7c59005

Please sign in to comment.