Categories
JavaScript Answers

How to use MongoDB with promises in Node.js?

Spread the love

To use MongoDB with promises in Node.js, we use async and await.

For instance, we write

const main = async () => {
  let client, db;
  try {
    client = await MongoClient.connect(mongoUrl, { useNewUrlParser: true });
    db = client.db(dbName);
    const dCollection = db.collection("collectionName");
    const result = await dCollection.find();
    return result.toArray();
  } catch (err) {
    console.error(err);
  } finally {
    client.close();
  }
};

to call connect to connect to the Mongo database.

We call db to get the database.

We call collection to get the collection.

And we call find to return a promise with the collection data.

We call toArray to convert the data to an array.

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 *