-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongodb.ts
36 lines (29 loc) · 1.02 KB
/
mongodb.ts
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
import { MongoClient } from "mongodb"
if (!process.env.MONGODB_URI) {
throw new Error("Please add your MongoDB URI to .env.local")
}
const uri = process.env.MONGODB_URI
const options = {}
let client
let clientPromise: Promise<MongoClient>
if (process.env.NODE_ENV === "development") {
// In development mode, use a global variable so that the value
// is preserved across module reloads caused by HMR (Hot Module Replacement).
const globalWithMongo = global as typeof globalThis & {
_mongoClientPromise?: Promise<MongoClient>
}
if (!globalWithMongo._mongoClientPromise) {
client = new MongoClient(uri, options)
globalWithMongo._mongoClientPromise = client.connect()
}
clientPromise = globalWithMongo._mongoClientPromise
} else {
// In production mode, it's best to not use a global variable.
client = new MongoClient(uri, options)
clientPromise = client.connect()
}
export async function connectToDatabase() {
const client = await clientPromise
const db = client.db("todo-app")
return { client, db }
}