-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
var MongoClient = require("mongodb").MongoClient | ||
|
||
|
||
const uri = process.env.MONGOURL | ||
const options = { | ||
useUnifiedTopology: true, | ||
useNewUrlParser: true, | ||
} | ||
|
||
let client = null; | ||
let clientPromise | ||
|
||
if (!process.env.MONGOURL) { | ||
throw new Error("Please add your Mongo URI to .env.local") | ||
} | ||
|
||
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). | ||
if (!global._mongoClientPromise) | ||
{ | ||
client = new MongoClient(uri, options) | ||
global._mongoClientPromise = client.connect() | ||
} | ||
clientPromise = global._mongoClientPromise | ||
} | ||
else | ||
{ | ||
// In production mode, it's best to not use a global variable. | ||
client = new MongoClient(uri, options) | ||
clientPromise = client.connect() | ||
} | ||
|
||
|
||
// Export a module-scoped MongoClient promise. By doing this in a | ||
// separate module, the client can be shared across functions. | ||
export default clientPromise |