Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,13 @@ const queries: (Record<string, unknown> | [Record<string, unknown>, Record<strin
{ $and: [{ $or: [{ name: "a" }, { status: { $eq: "b" } }] }, { active: true }] },
{ $and: [{ $or: { name: "a", status: { $eq: "b" } } }, { active: true }] },
],
// nested $or inside $or is not merged into a plain object (which would mean AND)
{ $or: [{ $or: { name: "a", status: "b" } }, { active: true }] },
// nested $and inside $and is merged
[
{ $and: [{ $and: { name: "a", status: "b" } }, { $or: { active: true, age: 1 } }] },
{ $and: [{ name: "a", status: "b" }, { $or: { active: true, age: 1 } }] },
],
]

describe("query roundtrip: parse → stringify", () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,15 +211,17 @@ const groupToObject = (

if (normalChildren.length > 0) {
result[`$${groupOperator}`] = normalChildren.map((child) => {
// Same-operator group with multiple mergeable conditions: flatten to merged object
// (avoids redundant nesting like $and: [{ $and: { ... } }] inside $and array)
// AND group inside AND with multiple mergeable conditions: flatten to merged object
// (avoids redundant nesting like $and: [{ $and: { ... } }] inside $and array).
// Not done for OR, since the fields of a plain object are always ANDed.
if (child.type === "group") {
const groupChild = child as QueryNode & { type: "group" }
const gc = groupChild.children
const gcNormal = gc.filter((c) => !c.not)
const gcNegated = gc.filter((c) => c.not)
if (
groupChild.groupOperator === groupOperator &&
groupOperator === "and" &&
groupChild.groupOperator === "and" &&
gc.length > 1 &&
gcNegated.length === 0 &&
canMergeChildren(gcNormal)
Expand Down
Loading