Nodejs – Connect MongoDB with Node app using MongooseJS
Source code explanation: Line 2 : It ‘requires’ or imports the mongoose package in our app. Line 4 : It assigns the connection string (which contains the info about connection to database) to our mongoDB variable. Line 6 : These lines help in establishing or ‘open’ or fire up a connection with the database mentioned mentioned in the mongoDB variable. The first argument to the mongoose.connect() function is the connection string(the mongoDB variable). Line 10 : The mongoose.connect() function returns the connection the database as mongoose.connection which we assign to the db variable. Line 14 : This line logs the message into the console when the connection to the database has been made and returned. It listens for ‘connected’ event and when the event fires, the function() comprising of line 14,15,16 gets executed. Line 19 : This line logs the message into the console when the connection to the database has been made and returned. It listens for ‘error’ event and when the event fires, the function() comprising of line 19,20,21 gets executed. After writing the source code open up a terminal or the command prompt(in case of windows users) and navigate to your project directory. then write the command npm install mongoose as shown in the image below:
The above command will create a ‘node_modules’ folder in your current directory or folder and download the necessary files there. If you are following until now, all the preparation is done and now we can test our connection to database. Write node app.js to start the app.