File size: 1,852 Bytes
6e13570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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 };