Skip to content

Commit

Permalink
fix(client): use connection db option as default database name (#223)
Browse files Browse the repository at this point in the history
  • Loading branch information
erfanium authored Jul 29, 2021
1 parent becde6f commit 7874818
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
5 changes: 4 additions & 1 deletion src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { assert } from "../deps.ts";

export class MongoClient {
#cluster?: Cluster;
#defaultDbName = "admin";

async connect(
options: ConnectOptions | string,
Expand All @@ -15,6 +16,8 @@ export class MongoClient {
const parsedOptions = typeof options === "string"
? await parse(options)
: options;

this.#defaultDbName = parsedOptions.db;
const cluster = new Cluster(parsedOptions);
await cluster.connect();
await cluster.authenticate();
Expand Down Expand Up @@ -49,7 +52,7 @@ export class MongoClient {
return await this.#cluster.protocol.commandSingle(db, body);
}

database(name: string): Database {
database(name = this.#defaultDbName): Database {
assert(this.#cluster);
return new Database(this.#cluster, name);
}
Expand Down
12 changes: 10 additions & 2 deletions tests/cases/02_connect.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { assert } from "../test.deps.ts";
import { assert, assertEquals } from "../test.deps.ts";
import { MongoClient } from "../../src/client.ts";

const hostname = "127.0.0.1";
Expand All @@ -13,7 +13,7 @@ export default function connectTests() {
client.close();
});

Deno.test("testconnect With Options", async () => {
Deno.test("test connect With Options", async () => {
const client = new MongoClient();
await client.connect({
servers: [{ host: hostname, port: 27017 }],
Expand All @@ -24,4 +24,12 @@ export default function connectTests() {
assert(names.length > 0);
client.close();
});

Deno.test("test default database name from connection options", async () => {
const client = new MongoClient();
await client.connect(`mongodb://${hostname}:27017/my-db`);
const db = client.database();
assertEquals(db.name, "my-db");
client.close();
});
}

0 comments on commit 7874818

Please sign in to comment.