Skip to content

Instantly share code, notes, and snippets.

@kiranvj
Last active October 28, 2024 09:03
Show Gist options
  • Save kiranvj/5933a42c0d8f9ae2417768de926cc785 to your computer and use it in GitHub Desktop.
Save kiranvj/5933a42c0d8f9ae2417768de926cc785 to your computer and use it in GitHub Desktop.
Nodejs/NextJS reusable mongodb connection and CURD operations
// 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;
}
}
@kiranvj
Copy link
Author

kiranvj commented Oct 28, 2024

Fetching data using findOne

import { connectToDatabase } from './utils/mongodb';
  
export async function getUserDetails(email) {
  const { db } = await connectToDatabase();

  const findOptions = { email: email };
  const projection = {};

  const user = await db.collection('users').findOne(findOptions, projection);
  return user;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment