Last active
October 28, 2024 09:03
-
-
Save kiranvj/5933a42c0d8f9ae2417768de926cc785 to your computer and use it in GitHub Desktop.
Nodejs/NextJS reusable mongodb connection and CURD operations
This file contains hidden or 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
// MongoDB connection | |
import { MongoClient } from 'mongodb'; // install package first | |
const { MONGODB_URI/* connection string*/, MONGODB_DB /*db name*/ } = process.env; | |
if (!MONGODB_URI) { | |
throw new Error( | |
'Please define the MONGODB_URI environment variable inside .env.local' | |
); | |
} | |
if (!MONGODB_DB) { | |
throw new Error( | |
'Please define the MONGODB_DB environment variable inside .env.local' | |
); | |
} | |
/** | |
* Global is used here to maintain a cached connection across hot reloads | |
* in development. This prevents connections growing exponentially | |
* during API Route usage. | |
*/ | |
let cached = global.mongo; | |
if (!cached) { | |
cached = global.mongo = { conn: null, promise: null }; | |
} | |
export async function connectToDatabase() { | |
if (cached.conn) { | |
return cached.conn; | |
} | |
if (!cached.promise) { | |
const opts = { | |
useNewUrlParser: true, | |
useUnifiedTopology: true, | |
}; | |
cached.promise = MongoClient.connect(MONGODB_URI, opts).then((client) => { | |
return { | |
client, | |
db: client.db(MONGODB_DB), | |
}; | |
}); | |
try { | |
cached.conn = await cached.promise; | |
if (!cached.conn) { | |
console.log('ERROR: Database error.'); | |
} | |
} catch (error) { | |
console.log('ERROR: Database error.' + error); | |
} | |
} | |
return cached.conn; | |
} | |
/** | |
* Close the db connection | |
*/ | |
export async function closeDatabase() { | |
if (cached.conn) { | |
await cached.conn.client.close(); | |
cached.conn = null; | |
cached.promise = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fetching data using
findOne