Akercode.com

Mongoose Connect with Async/Await

Mongoose is an Object Data Modeling (ODM) library for Node.js and is used to interact with MongoDB databases.

Database Connection

This is the straightforward method for connecting to the database that is described in the documentation, and what you see in most tutorials:

const server = '127.0.0.1:27017';
const database = 'test';

mongoose.connect(`mongodb://${server}/${database}`, { useNewUrlParser: true })
  .then(() => {
    console.log('Successfully connected to MongoDB!');
  })
  .catch(err => {
    console.log('Connection failed', err);
  });

Async/Await

async before a function means a function that always returns a promise.

await which works only inside an async function suspends the function execution until the promise settles, then it returns the result.

Mongoose connect with an async arrow function:

(async () => {
  try {
    await mongoose.connect(`mongodb://${server}/${database}`);
  } catch (err) {
    console.log('Connection failed', err);
  }
})()

Mongoose connect with an async arrow function saved as a named variable:

const dbConnect = async () => {
  try {
    await mongoose.connect(`mongodb://${server}/${database}`);
  } catch (err) {
    console.log('Connection failed', err);
  }
}
// Will only connect when the function is invoked
dbConnect();

Since the then() method returns a promise, we can use it to verify that the database connection was successful.

const dbConnect = async () => {
  try {
    await mongoose.connect(`mongodb://${server}/${database}`);
  } catch (err) {
    console.log('Connection failed', err);
  }
}
// Will only connect when the function is invoked
dbConnect().then(() => {
  console.log('Successfully connected to MongoDB!');
})