Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/sort.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ function isReadonlyArray<T>(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 */
Expand Down
31 changes: 31 additions & 0 deletions test/integration/crud/find.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
21 changes: 21 additions & 0 deletions test/unit/sort.test.ts
Original file line number Diff line number Diff line change
@@ -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' }]])
);
});
});
});
Loading