diff --git a/src/sort.ts b/src/sort.ts index 0b239ddd49..7625937ca5 100644 --- a/src/sort.ts +++ b/src/sort.ts @@ -81,7 +81,7 @@ function isReadonlyArray(value: any): value is readonly T[] { /** @internal */ function pairToMap(v: readonly [string, SortDirection]): SortForCmd { - return new Map([[`${v[0]}`, prepareDirection([v[1]])]]); + return new Map([[`${v[0]}`, prepareDirection(v[1])]]); } /** @internal */ diff --git a/test/integration/crud/find.test.ts b/test/integration/crud/find.test.ts index 2b24254e2d..337b3d86f5 100644 --- a/test/integration/crud/find.test.ts +++ b/test/integration/crud/find.test.ts @@ -884,6 +884,37 @@ describe('Find', function () { test.equal('spam eggs and spam', items[0].s); }); + it('should correctly sort by text score given as a [field, direction] pair', async function () { + const configuration = this.configuration; + const db = client.db(configuration.db); + + const collection = db.collection('textSearchWithPairSort'); + await collection.createIndex({ title: 'text' }); + + await collection.insertMany([ + { title: 'The Godfather Part II' }, + { title: 'Casablanca' }, + { title: 'Harlem Nights' }, + { title: 'The Godfather' }, + { title: 'Godfather of Harlem' } + ]); + + const items = await collection + .find( + { $text: { $search: 'godfather harlem' } }, + { projection: { _id: false, title: true, score: { $meta: 'textScore' } } } + ) + .sort(['score', { $meta: 'textScore' }]) + .toArray(); + + expect(items.map(({ title }) => title)).to.deep.equal([ + 'Godfather of Harlem', + 'The Godfather', + 'Harlem Nights', + 'The Godfather Part II' + ]); + }); + it('should not mutate user-provided options', async function () { const configuration = this.configuration; const db = client.db(configuration.db); diff --git a/test/unit/sort.test.ts b/test/unit/sort.test.ts new file mode 100644 index 0000000000..19669feff3 --- /dev/null +++ b/test/unit/sort.test.ts @@ -0,0 +1,21 @@ +import { expect } from 'chai'; + +import { formatSort } from '../mongodb'; + +describe('formatSort', function () { + context('when the sort is a [field, direction] pair', function () { + it('formats a numeric direction', function () { + expect(formatSort(['alpha', -1])).to.deep.equal(new Map([['alpha', -1]])); + }); + + it('formats a string direction', function () { + expect(formatSort(['alpha', 'asc'])).to.deep.equal(new Map([['alpha', 1]])); + }); + + it('preserves a $meta direction', function () { + expect(formatSort(['alpha', { $meta: 'textScore' }])).to.deep.equal( + new Map([['alpha', { $meta: 'textScore' }]]) + ); + }); + }); +});