Created
September 2, 2020 14:42
-
-
Save cadd/2dacdfe7d95239c79dbd1fb0e5dbf563 to your computer and use it in GitHub Desktop.
Node MongoDB Connection
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
| 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; |
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
| 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