db.js 709 B

1234567891011121314151617181920212223242526
  1. // lib/db.js
  2. import { MongoClient } from "mongodb";
  3. const uri = process.env.MONGODB_URI;
  4. if (!uri) {
  5. throw new Error("Bitte setze MONGODB_URI in .env.docker / .env.local");
  6. }
  7. // Wir cachen die Verbindung über globalThis, damit Next.js nicht bei jedem Request
  8. // eine neue Verbindung aufmacht (wichtig im Dev & bei Hot Reload).
  9. let client;
  10. let clientPromise;
  11. if (!global._mongoClientPromise) {
  12. client = new MongoClient(uri);
  13. global._mongoClientPromise = client.connect();
  14. }
  15. clientPromise = global._mongoClientPromise;
  16. export async function getDb() {
  17. const client = await clientPromise;
  18. // Wenn im URI ein DB-Name steht (/rhl-lieferscheine), nimmt der Client den automatisch.
  19. return client.db();
  20. }