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

To get started, you'll need to have access to a MongoDB server, either on your computer's local network or in the cloud.

Follow the installation guide from the official documentation and start the mongodb service on Ubuntu with the command (You will also find guides for Windows & macOS i the left menu):

sudo systemctl start mongod

From the mongo shell, you can list dbs (databases) with the command:

show databases
show dbs

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

Type in the mongodb url (connection string) into the mongoose.connect() method and you are ready to go!

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!');
})

Disconnect From Database and Stop Mongo Service

When the node js application closes, the mongoose connection is terminated, but the mongodb service is likely to continue operating in the background.

If you are running Ubuntu, in the command prompt, type the following command to stop the mongodb service:

sudo service mongod stop