Biren Subudhi
Biren Subudhi
Explore posts from servers
DDeno
Created by Biren Subudhi on 3/6/2025 in #help
npm:mongodb connection issue, timeout
It's resolved, mongodb documentation for nodejs was useful. Since importing MongoClient from deno package (https://deno.land/x/[email protected]/mod.ts) was giving frequent BSONError: corrupt object bson so migrated to npm:mongodb
import { MongoClient, ServerApiVersion } from "npm:[email protected]";
// import "https://deno.land/[email protected]/dotenv/load.ts"; // Load .env variables

const MONGO_USERNAME = Deno.env.get("MONGO_USERNAME");
const MONGO_PASSWORD = Deno.env.get("MONGO_PASSWORD");
const MONGO_APP_NAME = Deno.env.get("MONGO_APP_NAME");
const MONGO_CLUSTER_NAME = Deno.env.get("MONGO_CLUSTER_NAME");

const uri = `mongodb+srv://${MONGO_USERNAME}:${MONGO_PASSWORD}@${MONGO_CLUSTER_NAME}/?retryWrites=true&w=majority&appName=${MONGO_APP_NAME}`;


// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
});

const connectToMongoDB = async () => {
try {
console.log("Connecting to MongoDB...");
await client.connect();
console.log("Successfully connected to MongoDB");
return client.db("Faydo");
} catch (err) {
console.error("Error connecting to MongoDB:", err);
throw err;
}
};

const db = await connectToMongoDB();

export default db;
import { MongoClient, ServerApiVersion } from "npm:[email protected]";
// import "https://deno.land/[email protected]/dotenv/load.ts"; // Load .env variables

const MONGO_USERNAME = Deno.env.get("MONGO_USERNAME");
const MONGO_PASSWORD = Deno.env.get("MONGO_PASSWORD");
const MONGO_APP_NAME = Deno.env.get("MONGO_APP_NAME");
const MONGO_CLUSTER_NAME = Deno.env.get("MONGO_CLUSTER_NAME");

const uri = `mongodb+srv://${MONGO_USERNAME}:${MONGO_PASSWORD}@${MONGO_CLUSTER_NAME}/?retryWrites=true&w=majority&appName=${MONGO_APP_NAME}`;


// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
});

const connectToMongoDB = async () => {
try {
console.log("Connecting to MongoDB...");
await client.connect();
console.log("Successfully connected to MongoDB");
return client.db("Faydo");
} catch (err) {
console.error("Error connecting to MongoDB:", err);
throw err;
}
};

const db = await connectToMongoDB();

export default db;
The serverApi object passed to MongoClient is important to connect mongodb using nodejs/deno.
2 replies