Skip to content

Commit c7bc6c2

Browse files
committed
fix(query): handle array fields in $in operator (#1277)
1 parent 500f8a6 commit c7bc6c2

File tree

2 files changed

+41
-12
lines changed

2 files changed

+41
-12
lines changed

src/runtime/query/match/index.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,9 @@ function createOperators (match: (...args: any[]) => boolean, operators: Record<
6969
/**
7070
* Match if item is in condition array
7171
**/
72-
$in: (item, condition) => ensureArray(condition).some(cond => match(item, cond)),
72+
$in: (item, condition) => ensureArray(condition).some(
73+
cond => Array.isArray(item) ? match(item, { $contains: cond }) : match(item, cond)
74+
),
7375

7476
/**
7577
* Match if item contains every condition or math every rule in condition array

test/features/query/match.test.ts

Lines changed: 38 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -74,17 +74,6 @@ describe('Match', () => {
7474
})
7575
})
7676

77-
test('$in', () => {
78-
const item = { id: 1, name: 'a', to: 'a', category: 'c1', nested: { users: ['Mahatma', 'Steve', 'Woodrow'] } }
79-
80-
expect(match(item, { name: { $in: ['a', 'b'] } })).toBe(true)
81-
expect(match(item, { category: { $in: 'c1' } })).toBe(true)
82-
expect(match(item, { category: { $in: ['c1', 'c2'] } })).toBe(true)
83-
expect(match(item, { category: { $in: ['c2', 'c3'] } })).toBe(false)
84-
85-
expect(match(item, { id: { $in: [1, 2] } })).toBe(true)
86-
})
87-
8877
test('$eq', () => {
8978
// string
9079
expect(match(item, { name: { $eq: 'a' } })).toBe(true)
@@ -187,4 +176,42 @@ describe('Match', () => {
187176
expect(match(item, { id: { $lte: 0 } })).toBe(false)
188177
})
189178
})
179+
180+
describe('$in ', () => {
181+
test('string filed', () => {
182+
const item = { id: 1, name: 'a', to: 'a', category: 'c1', nested: { users: ['Mahatma', 'Steve', 'Woodrow'] } }
183+
184+
expect(match(item, { name: { $in: ['a', 'b'] } })).toBe(true)
185+
expect(match(item, { category: { $in: 'c1' } })).toBe(true)
186+
expect(match(item, { category: { $in: ['c1', 'c2'] } })).toBe(true)
187+
expect(match(item, { category: { $in: ['c2', 'c3'] } })).toBe(false)
188+
189+
expect(match(item, { id: { $in: [1, 2] } })).toBe(true)
190+
})
191+
192+
test('array field', () => {
193+
const data = [
194+
{
195+
name: 'post1',
196+
tags: ['school', 'office']
197+
},
198+
{
199+
name: 'post2',
200+
tags: ['school', 'home']
201+
},
202+
{
203+
item: 'Maps',
204+
tags: ['office', 'storage']
205+
}
206+
]
207+
208+
const condition = { tags: { $in: ['school', 'home'] } }
209+
data.forEach((item) => {
210+
expect(match(item, condition)).toBe(
211+
item.tags.includes(condition.tags.$in[0]) ||
212+
item.tags.includes(condition.tags.$in[1])
213+
)
214+
})
215+
})
216+
})
190217
})

0 commit comments

Comments
 (0)