Skip to content

Commit

Permalink
Merge pull request #397 from AsPulse/fix/return-type-of-findAndModify
Browse files Browse the repository at this point in the history
findAndModify now returns T | null instead of T | undefined
  • Loading branch information
lucsoft committed Jun 8, 2023
2 parents a49057d + 239a10d commit 6e27e38
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/collection/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export class Collection<T extends Document> {
async findAndModify(
filter?: Filter<T>,
options?: FindAndModifyOptions<T>,
): Promise<T | undefined> {
): Promise<T | null> {
const result = await this.#protocol.commandSingle<{
value: T;
ok: number;
Expand Down
24 changes: 22 additions & 2 deletions tests/cases/03_curd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,26 @@ testWithTestDBClient("testInsertMany", async (db) => {
assertEquals(insertedIds.length, 2);
});

testWithTestDBClient("testFindAndModify-notfound", async (db) => {
const users = db.collection<{ username: string; counter: number }>(
"mongo_test_users",
);

const find = await users.findAndModify(
{
// this query matches no document
$and: [{ username: "a" }, { username: "b" }],
},
{
update: { $inc: { counter: 1 } },
new: false,
},
);

assert(find === null);
assert(find !== undefined);
});

testWithTestDBClient("testFindAndModify-update", async (db) => {
const users = db.collection<{ username: string; counter: number }>(
"mongo_test_users",
Expand All @@ -217,7 +237,7 @@ testWithTestDBClient("testFindAndModify-update", async (db) => {
new: true,
});

assert(updated !== undefined);
assert(updated !== null);
assertEquals(updated.counter, 6);
assertEquals(updated.username, "counter");
});
Expand All @@ -231,7 +251,7 @@ testWithTestDBClient("testFindAndModify-delete", async (db) => {
remove: true,
});

assert(updated !== undefined);
assert(updated !== null);
assertEquals(updated.counter, 10);
assertEquals(updated.username, "delete");

Expand Down

0 comments on commit 6e27e38

Please sign in to comment.