mongoose connect

  1. Import the mongoose module to the Node.js application using the require method.
const mongoose = require('mongoose');
  1. Establish a connection to the MongoDB database using the connect method of the mongoose object.
mongoose.connect('mongodb://localhost:27017/my_database', { useNewUrlParser: true, useUnifiedTopology: true });
  1. Handle the connection events such as error and open using the connection object provided by the mongoose module.
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("Connected to the database");
});