Skip to content

Instantly share code, notes, and snippets.

@chrisbrocklesby
Created August 29, 2021 02:00
Show Gist options
  • Save chrisbrocklesby/1e64a219b7206a9b4511eb3b715ea21f to your computer and use it in GitHub Desktop.
Save chrisbrocklesby/1e64a219b7206a9b4511eb3b715ea21f to your computer and use it in GitHub Desktop.
MongoDB Native Drive Example - (NodeJS / Export & Import / Await & Async)

MongoDB Native Drive Example

(NodeJS / Export & Import / Await & Async)

db.js

const mongodb = require('mongodb');

const url = 'CONNECTION_URL';
const options = {};
const database = 'DATABASE_NAME';
const client = new mongodb.MongoClient(url, options);

module.exports = {
  connect: async () => (await client.connect()).db(database),
  disconnect: () => client.close(),
  ...mongodb,
};

index.js

const { connect, disconnect, ObjectId } = require('./db');

async function sampleFunction() {
  const db = await connect();
  console.log(await db.collection('posts').find().toArray());
  disconnect();
}

sampleFunction();
@chrisbrocklesby
Copy link
Author

Hope this helps someone.

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