Skip to content

Instantly share code, notes, and snippets.

@cadd
Created September 2, 2020 14:42
Show Gist options
  • Select an option

  • Save cadd/2dacdfe7d95239c79dbd1fb0e5dbf563 to your computer and use it in GitHub Desktop.

Select an option

Save cadd/2dacdfe7d95239c79dbd1fb0e5dbf563 to your computer and use it in GitHub Desktop.
Node MongoDB Connection
import dotenv from 'dotenv';
import { MongoClient } from 'mongodb';
dotenv.config();
const client = new MongoClient(
process.env.MONGODB_URI,
{
useUnifiedTopology: true,
},
);
// Close the connection after the server is shut down
(async () => {
await client.connect();
// 'CTRL + C' -> 'SIGINT' means signal interrupt i.e. server shut down
process.on('SIGINT', () => {
client.close().then(() => {
console.info('SIGINT received: DB connection is closing');
// Avoid plugging up ports - ensures all processes are stopped
process.exit(0);
});
});
})();
export default client;
import client from './client';
// GOOD
export const addNewUser = async (newUser) => {
try {
return await client.db('throwaway').collection('users').insertOne(newUser);
} catch (err) {
throw new Error(err);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment