Step 7

Add the following to index.js

const option = {
  useNewUrlParser: true,
  useUnifiedTopology: true,
};

mongoose
  .connect(URI, option)
  .then(() => {
    console.log("Connected to MongoDB!");
  })
  .catch((err) => {
    console.log(err);
  });

We are using the connect method on mongoose object to establish a connection to our MongoDB cluster in the cloud.

The connect method takes two arguments and returns a Promise. The arguments are the database URI and an option object. You can read about available option parameters, in particular those that are important for tuning Mongoose, here (link opens to mongoose documentation).

Once the Promise returned by the connect method resolves, we print the message "Connected to MongoDB!". If the attempt to connect fails for any reason, the error will be printed to the terminal.

Run the demo application; if you have followed all the steps correctly, it will work and you will see "Connected to MongoDB!" printed in the terminal.

Mongoose emits events when e.g. a connection is established (or failed to establish due to an error). So, another pattern for working with Mongoose is the following that uses the event listeners on connection object:

mongoose.connect(URI, option);

mongoose.connection.on("open", () => {
  console.log("Connected to MongoDB!");
});

mongoose.connection.on("error", (err) => {
  console.log(err);
});

Run the demo application to check that this alternative approach works too. It might be a good idea to deliberately provide mongoose with e.g. wrong password and check that connection fails.