How to use MongoDB with promises in Node.js?

Sometimes, we want to use MongoDB with promises in Node.js.

In this article, we’ll look at how to use MongoDB with promises in Node.js.

How to use MongoDB with promises in Node.js?

To use MongoDB with promises in Node.js, we can use the MongoDB client methods with async and await.

For instance, we write

const {
  MongoClient
} = require('mongodb')

const connect = async () => {
  const url = 'mongodb://localhost:27017/example'
  const db = await MongoClient.connect(url)
  console.log(db)
}

to call MongoClient.connect with the database url to connect to the database at the given URL.

Then we get the db database connection handle with await.

await returns the resolve value from the promise returned by connect.

Conclusion

To use MongoDB with promises in Node.js, we can use the MongoDB client methods with async and await.