Categories
JavaScript Answers

How to use Node.js MongoDB driver async/await queries with JavaScript?

Spread the love

Sometimes, we want to use Node.js MongoDB driver async/await queries with JavaScript.

In this article, we’ll look at how to use Node.js MongoDB driver async/await queries with JavaScript.

How to use Node.js MongoDB driver async/await queries with JavaScript?

To use Node.js MongoDB driver async/await queries with JavaScript, we use await before database methods.

For instance, we write

const queryDb = async (query) => {
  let db, client;
  try {
    client = await MongoClient.connect(process.env.MONGODB_CONNECTION_STRING, {
      useNewUrlParser: true,
    });
    db = client.db(dbName);
    return await db.collection(collectionName).find(query).toArray();
  } finally {
    client.close();
  }
};

to define the queryDb function.

In it, we call MongoClient.connect to connect to the database with the connect string.

It returns a promise so we use await to get the client.

Then we get the database with client.db.

Then we call find to find an object in the collectionName collection and get the results from the promise returned with await.

We call close to close the connection in the finally block.

Conclusion

To use Node.js MongoDB driver async/await queries with JavaScript, we use await before database methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *