From b444336384ff8afce468bd7eda82123f4ab8b70d Mon Sep 17 00:00:00 2001 From: ERFANIUM Date: Wed, 28 Jul 2021 17:14:31 +0430 Subject: [PATCH] fix(client): use connection db option as default database name --- src/client.ts | 5 ++++- tests/cases/02_connect.ts | 12 ++++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/client.ts b/src/client.ts index 2bed2b20..7cf1c3fd 100644 --- a/src/client.ts +++ b/src/client.ts @@ -7,6 +7,7 @@ import { assert } from "../deps.ts"; export class MongoClient { #cluster?: Cluster; + #defaultDbName = "admin"; async connect( options: ConnectOptions | string, @@ -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(); @@ -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); } diff --git a/tests/cases/02_connect.ts b/tests/cases/02_connect.ts index 42d5c86b..dbaf6598 100644 --- a/tests/cases/02_connect.ts +++ b/tests/cases/02_connect.ts @@ -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"; @@ -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 }], @@ -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(); + }); }