Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(client): use connection db option as default database name #223

Merged
merged 1 commit into from
Jul 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
});
}