Skip to content

Commit

Permalink
Use pipeline $count, add test
Browse files Browse the repository at this point in the history
  • Loading branch information
DaddyWarbucks committed Oct 10, 2024
1 parent 0f1deb6 commit e6595b8
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
5 changes: 3 additions & 2 deletions packages/mongodb/src/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ export class MongoDbAdapter<
const aggregateParams = {
...params,
paginate: false,
pipeline: [...params.pipeline, { $count: 'total' }],
query: {
...params.query,
$select: [this.id],
Expand All @@ -222,8 +223,8 @@ export class MongoDbAdapter<
$limit: undefined
}
}
const result = await this.aggregateRaw(aggregateParams).then((result) => result.toArray())
return result.length
const [result] = await this.aggregateRaw(aggregateParams).then((result) => result.toArray())
return result.total
}

const model = await this.getModel(params)
Expand Down
22 changes: 12 additions & 10 deletions packages/mongodb/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,6 @@ const testSuite = adapterTests([
'params.adapter + multi'
])

const defaultPaginate = {
default: 10,
max: 50
}

describe('Feathers MongoDB Service', () => {
const personSchema = {
$id: 'Person',
Expand Down Expand Up @@ -573,12 +568,19 @@ describe('Feathers MongoDB Service', () => {
it('can count documents with aggregation', async () => {
const service = app.service('people')
const paginateBefore = service.options.paginate
service.options.paginate = defaultPaginate
const query = { age: { $gte: 25 } }
const findResult = await app.service('people').find({ query })
const aggregationResult = await app.service('people').find({ query, pipeline: [] })

assert.deepStrictEqual(findResult.total, aggregationResult.total)
const test = async (paginate: any) => {
service.options.paginate = paginate
const query = { age: { $gte: 25 } }
const findResult = await app.service('people').find({ query })
const aggregationResult = await app.service('people').find({ query, pipeline: [] })
assert.deepStrictEqual(findResult.total, aggregationResult.total)
}

await test({ default: 10, max: 50 })
// There are 2 people with age >= 25.
// Test that aggregation works when results are less than default
await test({ default: 1, max: 50 })

service.options.paginate = paginateBefore
})
Expand Down

0 comments on commit e6595b8

Please sign in to comment.