How can I use async-await with MongoClient
I solved it like this, only opening one connection:
db.js
const MongoClient = require('mongodb').MongoClient;let db;const loadDB = async () => { if (db) { return db; } try { const client = await MongoClient.connect('mongodb://localhost:27017/dbname'); db = client.db('dbname'); } catch (err) { Raven.captureException(err); } return db;};module.exports = loadDB;
index.js
const loadDB = require('./db');const db = await loadDB();await db.collection('some_collection').insertOne(...);
What about wrapping it in an async function?
var MongoClient = require('mongodb').MongoClient,var url = "mongodb://localhost:27017/myDB";var test = async function () { return await MongoClient.connect(url);}module.exports = test;
Is your module wrapper an async function as well? You need the await
keyword to be in an async function.