db.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // lib/db.js
  2. import mongoose from "mongoose";
  3. // Reuse the connection across hot reloads in dev and across route handler invocations.
  4. const globalForMongoose = globalThis;
  5. const cached =
  6. globalForMongoose.__mongooseCache ||
  7. (globalForMongoose.__mongooseCache = { conn: null, promise: null });
  8. async function connectMongoose() {
  9. const uri = process.env.MONGODB_URI;
  10. if (!uri) {
  11. throw new Error("MONGODB_URI environment variable is not set");
  12. }
  13. if (cached.conn) {
  14. return cached.conn;
  15. }
  16. if (!cached.promise) {
  17. cached.promise = mongoose
  18. .connect(uri, {
  19. // Fail fast if someone queries before we are connected
  20. bufferCommands: false,
  21. })
  22. .then((m) => m);
  23. }
  24. cached.conn = await cached.promise;
  25. return cached.conn;
  26. }
  27. /**
  28. * Returns the native MongoDB db handle (from the active Mongoose connection).
  29. * This also ensures the Mongoose connection is established.
  30. */
  31. export async function getDb() {
  32. await connectMongoose();
  33. const db = mongoose.connection?.db;
  34. if (!db) {
  35. throw new Error("MongoDB connection is not ready");
  36. }
  37. return db;
  38. }