Connecting MongoDB with Express app using Mongoose JS

Connecting MongoDB with Express app using Mongoose JS

To connect MongoDB database with an Express application we need a npm module called mongoose.js

How to install mongoose.js

npm install mongoose

After installing mongoose,all we need is to add this code into the application main server file(generally app.js)

let mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/Name-of-dataBase-of-your-choice',(error)=>{
     if(error){
         console.log(error);
}else{
        console.log('Database connected successfully');
}
})

If everything went well, you will see a message in the terminal - Database connected successfully

⚠️ Before trying to connect application with database , we first ensure that demon process of mongodb is running.

Command to run demon process(for Linux users) -

  1. Open terminal
  2. Type command
sudo systemctl start mongod

Happy Coding