AndreaNotes1's picture
Upload 36 files
6e13570 verified
Raw History Blame Contribute Delete
1.85 kB
const mongoose = require("mongoose");
const { env } = require("./env");
const logger = require("../utils/logger");
mongoose.set("strictQuery", true);
async function connectDB() {
if (!env.mongoUri) {
throw new Error("MONGODB_URI is not set. Copy .env.example to .env and configure your Atlas connection string.");
}
mongoose.connection.on("connected", () => logger.info("MongoDB connected"));
mongoose.connection.on("error", (err) => logger.error("MongoDB connection error", { error: err.message }));
mongoose.connection.on("disconnected", () => logger.warn("MongoDB disconnected"));
try {
await mongoose.connect(env.mongoUri, {
// Modern mongoose driver already defaults to these; kept explicit for clarity.
autoIndex: env.nodeEnv !== "production", // build indexes lazily in prod via migration/ops task
maxPoolSize: 20,
serverSelectionTimeoutMS: 10000,
});
} catch (err) {
if (err.code === "ECONNREFUSED" && err.syscall === "querySrv") {
throw new Error(
"Could not resolve your MongoDB Atlas SRV connection string " +
`(${err.hostname || "the cluster hostname"}). This almost always means your network, router, ` +
"or ISP is blocking DNS SRV record lookups (common on home/office Wi-Fi) β€” it is not a code " +
"or credentials problem. Fix: in Atlas, go to your cluster β†’ Connect β†’ Drivers, and use the " +
"'standard connection string' (starts with mongodb:// and lists three hosts) instead of the " +
"mongodb+srv:// one, then update MONGODB_URI in your .env. See server/README.md for details."
);
}
throw err;
}
return mongoose.connection;
}
async function disconnectDB() {
await mongoose.disconnect();
}
module.exports = { connectDB, disconnectDB };