I have this file to test a connection to my MongoDB database:
import { MongoClient } from "./deps.ts";
import { load } from "./deps.ts";
await load({ export: true });
const mongoUri = Deno.env.get("MONGODB_URI");
if (!mongoUri) {
throw new Error("MONGODB_URI is not defined in the environment variables");
}
const client = new MongoClient();
try {
console.log("Attempting to connect to MongoDB...");
await client.connect(mongoUri);
console.log("Successfully connected to MongoDB!");
// Test the connection
const db = client.database("vitalityVista");
const collections = await db.listCollections().toArray();
console.log("Available collections:", collections);
} catch (error) {
console.error("MongoDB connection error:", error);
throw error;
} finally {
await client.close();
}
And I am getting this error: MongoDB connection error:
Error: MongoError: "Connection failed: MongoError: {\"ok\":0,\"errmsg\":\"bad auth : authentication failed\",\"code\":8000,\"codeName\":\"AtlasError\"}"
at MongoClient.connect (https://deno.land/x/mongo@v0.32.0/src/client.ts:46:13)
at eventLoopTick (ext:core/01_core.js:175:7)
at async file:///C:/Users/enman/OneDrive - BYU-Idaho/vitality_vista/backend/test_mongo.ts:15:3
error: Uncaught (in promise) Error: MongoError: "Connection failed: MongoError: {\"ok\":0,\"errmsg\":\"bad auth : authentication failed\",\"code\":8000,\"codeName\":\"AtlasError\"}"
throw new MongoDriverError(`Connection failed: ${e.message || e}`);
^
at MongoClient.connect (https://deno.land/x/mongo@v0.32.0/src/client.ts:46:13)
at eventLoopTick (ext:core/01_core.js:175:7)
at async file:///C:/Users/enman/OneDrive - BYU-Idaho/vitality_vista/backend/test_mongo.ts:15:3
The connection string is correct because I connected to the database using mongosh and had no issues with it, which could be the cause? my password or user do not have special characters as well.
Adding authMechanism=SCRAM-SHA-1 in the connection string did the trick for me.