MongoDB is widely known NoSQL database and express.js is most popular javascript framework. Let’s see how mongoDB can be connected with express.js application.
Step 1 : Download and Install mongoDB Server and mongoDB Compass
To Connect mongoDB and mongoDB Compass with Express.js first you need install mongoDB database in you MacOS or Windows or Linux System. If you haven’t installed these tools go through these link to download and install :
Install mongoDB Community Server : https://www.mongodb.com/try/download/community
Install mongoDB Compass : https://www.mongodb.com/try/download/compass
Once you download and install mongoDB server and Compass in your system. Create database with mongoDB Compass.
Step 2 : Install npm packages
Now Create Folder called DBConnectApp and open with VSCode or any code editor.
Then Open Terminal and initialize the npm package with npm init command on terminal, this will create package.json file on the DBConnectApp folder.
Now you have to install these npm packages : express, mongoose, dotenv, nodemon as dev dependency
npm i express mongoose dotenv
And install nodemon as dev dependency. For that you can just type this command on terminal
npm install --save-dev nodemon
Then make changes on package.json file on “type”:”module” and “scripts”:”nodemon index.js” as shown below in the code.
Step 3 : Configure .env file with Port and mongoDB Url
The .env file stores configuration variables, so let’s add port where application will run and mongoDB url with database name.
Step 4 : Write Code for Connection
Create an index.js file, import all packages, and create an app instance. Next, obtain the port and MongoDB URL. Finally, use Mongoose to connect.
The output will shown as below :
Step 4 : Write Code for Connection
Now Let’s see how you can get the users data from the database. For that let’s create a json document in mongodb compass with the following user data name and age. Once you create json document. Now let’s write the code to get data from database.
- First, define the schema for the user data using Mongoose
- Then, create a Mongoose model called “UserModel” based on the userSchema
- Finally, set up a route in the Express application to handle GET requests to /getUsers
Now, simply check the output at the endpoint “http://localhost:8000/getUsers” using Postman or browser, and the output will look like this:
Github Link for the source code : https://github.com/arjungautam1/mongodbconnectapp
If you got stucked in the above process watch the fully explained following video :
For building CRUD application I have got separate blog check it out.
For CRUD using express.js / Node.js / mongoDB : https://codewitharjun.com/restful-crud-using-node-js-express-js-mongodb/