Nodejs – Connect MongoDB with Node app using MongooseJS
Connect the MongoDB database using MongooseJS to our NodeJS application Before we dive into looking how the mongoDB connects with a nodejs app using mongooseJS, lets get a brief intro to these technologies which are ruling the web development domain of today.
mongoDB: MongoDB is a cross-platform and open-source document-oriented database, a kind of NoSQL database. As a NoSQL(not only SQL) database, MongoDB shuns the relational database’s table-based structure to adapt JSON-like documents that have dynamic schemas which it calls BSON(Binary JSON).Explaining what these terms mean is not the purpose of this article but a brief outlook is here.
MongooseJS: Mongoose or MongooseJS is a MongoDB object modeling(ODM) tool designed to work in an asynchronous environment. Basically, it is a package that we will use to interact(query, update, manipulate) with our MongoDB database in our nodeJS app. We would install or ‘require’ mongooseJS in our app with NPM(node packaging manager).
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.
Please Login to comment...