Skip to content

Commit

Permalink
feat: implement replaceOne (#281)
Browse files Browse the repository at this point in the history
* feat: implement replaceOne

* chore: use optional chaining instead of ternary operator
  • Loading branch information
erfanium authored Oct 22, 2021
1 parent 1ace025 commit 8adce47
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
34 changes: 33 additions & 1 deletion src/collection/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ export class Collection<T> {
multi: false,
});
return {
upsertedId: upsertedIds ? upsertedIds[0] : undefined,
upsertedId: upsertedIds?.[0],
upsertedCount,
matchedCount,
modifiedCount,
Expand All @@ -232,6 +232,38 @@ export class Collection<T> {
});
}

async replaceOne(
filter: Filter<T>,
replacement: InsertDocument<T>,
options?: UpdateOptions,
) {
if (hasAtomicOperators(replacement)) {
throw new MongoInvalidArgumentError(
"Replacement document must not contain atomic operators",
);
}

const { upsertedIds = [], upsertedCount, matchedCount, modifiedCount } =
await update(
this.#protocol,
this.#dbName,
this.name,
filter,
replacement,
{
...options,
multi: false,
},
);

return {
upsertedId: upsertedIds?.[0],
upsertedCount,
matchedCount,
modifiedCount,
};
}

async deleteMany(
filter: Filter<T>,
options?: DeleteOptions,
Expand Down
17 changes: 16 additions & 1 deletion tests/cases/03_curd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,21 @@ export default function curdTests() {
assertEquals(result.upsertedCount, 1);
});

testWithClient("testReplaceOne", async (client) => {
const db = client.database("test");
const users = db.collection<IUser>("mongo_test_users");
const result = await users.replaceOne({ username: "USER2" }, {
username: "USER3",
});

assertEquals(result, {
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0,
upsertedId: undefined,
});
});

testWithClient("testDeleteOne", async (client) => {
const db = client.database("test");
const users = db.collection<IUser>("mongo_test_users");
Expand Down Expand Up @@ -317,7 +332,7 @@ export default function curdTests() {
const db = client.database("test");
const users = db.collection<IUser>("mongo_test_users");
const user1 = await users.distinct("username");
assertEquals(user1, ["USER2", "user1"]);
assertEquals(user1, ["USER3", "user1"]);
});

testWithClient("testDropConnection", async (client) => {
Expand Down

0 comments on commit 8adce47

Please sign in to comment.