Skip to content

Commit

Permalink
fix: support complex operators in filter query related to the _id fie…
Browse files Browse the repository at this point in the history
…ld transformation
  • Loading branch information
playerx committed Jul 26, 2021
1 parent 4649862 commit 554bbe5
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
23 changes: 22 additions & 1 deletion src/__tests__/mangoRepo.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Db, MongoClient } from 'mongodb'
import { Db, MongoClient, ObjectId } from 'mongodb'
import { getClient } from '../common/getClient'
import {
MangoDocumentDates,
Expand Down Expand Up @@ -166,6 +166,27 @@ describe('mangoRepo', () => {
expect(count19).toBe(1)
expect(count20).toBe(0)
})

it('should query documents by _id filter (complex)', async () => {
const repo = new MangoRepo<User>(db, collectionName)

const id1 = new ObjectId().toHexString()
const id2 = new ObjectId().toHexString()

const createdCount = await repo.createMany([
{ id: id1, nickname: 'U1', age: 31 },
{ id: id2, nickname: 'U2', age: 31 },
{ nickname: 'U3', age: 31 },
{ nickname: 'U3', age: 30 },
])

const count1 = await repo.count({ id: { $in: [id1] } })
const count2 = await repo.count({ id: { $in: [id1, id2] } })

expect(createdCount).toBe(4)
expect(count1).toBe(1)
expect(count2).toBe(2)
})
})

describe('feature: idMapping', () => {
Expand Down
26 changes: 26 additions & 0 deletions src/domain/transformDocument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,13 +113,39 @@ export function prepareFilterQuery<TDocument>(
_id: new ObjectId(_id),
}
break

case 'object':
{
result = {
...result,
_id: Object.fromEntries(
Object.entries(_id).map(([key, value]) => [
key,
value
? Array.isArray(value)
? value.map(x => mapToObjectId(x))
: mapToObjectId(value)
: value,
]),
),
}
}
break
}
}
}

return result
}

function mapToObjectId(value: unknown) {
if (typeof value === 'string' && value.length === 24) {
return new ObjectId(value)
}

return value
}

export function prepareUpdateQuery<TDocument>(
query: UpdateQuery<TDocument>,
dateNow: Date,
Expand Down

0 comments on commit 554bbe5

Please sign in to comment.