Meetinger
Meetinger

Reputation: 375

Await the database connection

I need to wait the MongoDB database connection.

I have a function that makes a connection and puts a database object into a global variable. I also have a server startup function in which I want to call the database connection function

async function connectDB() {
    const client = new MongoClient(config.DBURL, {useNewUrlParser: true, useUnifiedTopology: true});
    await client.connect(err => {
        if (err) {
            throw err
        }
        global.dbClient = client
        global.db = client.db("db")
        console.log("Database Connected!")
    });
}

module.exports = {
    connectDB: connectDB
}
const connectDB = require('./db').connectDB
app.listen(port, async () => {
    await connectDB()
    console.log('Server started on: ' + port);
});

Upvotes: 1

Views: 1019

Answers (1)

Kelvin Schoofs
Kelvin Schoofs

Reputation: 8718

I assume your problem is that await client.connect doesn't actually wait. That would indicate that client.connect doesn't actually return a Promise. But you can wrap it in your own:

async function connectDB() {
    const client = new MongoClient(config.DBURL, { useNewUrlParser: true, useUnifiedTopology: true });
    return new Promise((resolve, reject) => {
        client.connect(err => {
            if (err) return reject(err);
            global.dbClient = client;
            global.db = client.db("db");
            console.log("Database Connected!");
            resolve(client);
        });
    });
}

Upvotes: 1

Related Questions