MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Come posso usare async-await con MongoClient

L'ho risolto in questo modo, aprendo solo una connessione:

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(...);