From 4e9baf39579510b0a0b9aa985cf2f6914c6e77bc Mon Sep 17 00:00:00 2001 From: ChengLei Shao Date: Thu, 3 Mar 2022 12:09:25 +0800 Subject: [PATCH] fix: array operator query error (#217) --- .../__tests__/operator/array-operator.test.ts | 15 ++++++++++++++ packages/database/src/filter-parser.ts | 20 +++++++++++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/packages/database/src/__tests__/operator/array-operator.test.ts b/packages/database/src/__tests__/operator/array-operator.test.ts index 26690f284..e6145b91c 100644 --- a/packages/database/src/__tests__/operator/array-operator.test.ts +++ b/packages/database/src/__tests__/operator/array-operator.test.ts @@ -152,6 +152,21 @@ describe('array field operator', function () { expect(filter2[0].get('name')).toEqual(t2.get('name')); }); + test('$anyOf with $and', async () => { + const filter3 = await Test.repository.find({ + filter: { + $and: [ + { + 'selected.$anyOf': ['aa'], + }, + ], + }, + }); + + expect(filter3.length).toEqual(1); + expect(filter3[0].get('name')).toEqual(t2.get('name')); + }); + test('$anyOf', async () => { const filter3 = await Test.repository.find({ filter: { diff --git a/packages/database/src/filter-parser.ts b/packages/database/src/filter-parser.ts index 4a21935ce..9dcee2d1b 100644 --- a/packages/database/src/filter-parser.ts +++ b/packages/database/src/filter-parser.ts @@ -121,10 +121,12 @@ export default class FilterParser { } else if (typeof opKey === 'function') { skipPrefix = origins.join('.'); - value = opKey(lodash.get(unflatten(originalFiler), skipPrefix), { + const queryValue = lodash.get(unflatten(originalFiler), skipPrefix); + + value = opKey(queryValue, { db: this.database, path: skipPrefix, - fieldName: skipPrefix.replace(`.${firstKey}`, ''), + fieldName: this.getFieldNameFromQueryPath(skipPrefix), model: this.model, }); break; @@ -220,4 +222,18 @@ export default class FilterParser { debug('where %o, include %o', where, include); return { where, include: toInclude(include) }; } + + private getFieldNameFromQueryPath(queryPath: string) { + const paths = queryPath.split('.'); + let fieldName; + for (const path of paths) { + if (path.startsWith('$') || !lodash.isNaN(parseInt(path))) { + continue; + } + + fieldName = path; + } + + return fieldName; + } }