Mongoose Connect Using Async/Await

Jan 7, 2021

Mongoose has two ways of connecting to a MongoDB database, connect() and createConnection(). You can use these within an async function as follows:

// Connect to a MongoDB server running on 'localhost:27017' and use the
// 'test' database.
await mongoose.connect('mongodb://localhost:27017/test', {
  useNewUrlParser: true // Boilerplate for Mongoose 5.x
});

and for createConnection()

// Connect to a MongoDB server running on 'localhost:27017' and use the
// 'test' database.
await mongoose.createConnection('mongodb://localhost:27017/test', {
  useNewUrlParser: true
});

Want to become your team's MongoDB expert? "Mastering Mongoose" distills 8 years of hard-earned lessons building Mongoose apps at scale into 153 pages. That means you can learn what you need to know to build production-ready full-stack apps with Node.js and MongoDB in a few days. Get your copy!

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Mongoose Tutorials