Skip to content

Commit

Permalink
Add sort feature and fix #111 (#146)
Browse files Browse the repository at this point in the history
  • Loading branch information
jctaoo authored Dec 6, 2020
1 parent 8167e0e commit 939af5e
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/collection/commands/find.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,9 @@ export class FindCursor<T> extends CommandCursor<T> {
this.#context.options.skip = skip;
return this;
}

sort(sort: Document): this {
this.#context.options.sort = sort;
return this;
}
}
39 changes: 39 additions & 0 deletions tests/curd.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ interface IUser {
username: string;
password: string;
_id: { $oid: string };
uid?: number;
date?: Date;
}

Expand Down Expand Up @@ -251,3 +252,41 @@ testWithClient("testDropConnection", async (client) => {
await db.collection("mongo_test_users_2").drop();
await db.collection("mongo_test_users").drop();
});

testWithClient("testFindWithSort", async (client) => {
const db = client.database("test");
const users = db.collection<IUser>("mongo_test_users");

const condition = { uid: { $ne: null } };

// prepare data
for (let i = 0; i < 10; i++) {
await users.insertOne({
username: "testFindWithSort",
password: "pass1",
uid: i,
});
}
const all = await users.find().toArray();

// test sorting
const acceding = await users
.find(condition, { sort: { uid: 1 } })
.toArray();
const descending = await users
.find(condition, { sort: { uid: -1 } })
.toArray();

assertEquals(
acceding,
all.sort((lhs, rhs) => {
return lhs.uid! - rhs.uid!;
}),
);
assertEquals(
descending,
all.sort((lhs, rhs) => {
return -lhs.uid! - rhs.uid!;
}),
);
});

0 comments on commit 939af5e

Please sign in to comment.