,

Building a Server-Side Web App with Node JS & Express JS: Connecting to MongoDB | Part 5

Posted by

How to Create a Server-Side Web App using Node JS & Express JS | How To Connect to MongoDB | Part 5

How to Create a Server-Side Web App using Node JS & Express JS | How To Connect to MongoDB | Part 5

Creating a server-side web app using Node JS and Express JS is a powerful way to build scalable and efficient web applications. In this tutorial, we will learn how to connect to a MongoDB database using a Node JS application. This is part 5 of our series on building a server-side web app.

Step 1: Set Up the Project

First, create a new directory for your project and navigate to it using the terminal. Then, run the following command to initialize a new Node JS project:

npm init -y

This will create a package.json file with default values. Next, install the necessary dependencies using the following commands:

npm install express mongoose body-parser

Express is a minimal and flexible Node JS web application framework that provides a robust set of features for web and mobile applications. Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment, while body-parser is a middleware for parsing incoming request bodies in a Node JS application.

Step 2: Connect to MongoDB

Create a new file called app.js and add the following code to it:


const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Could not connect to MongoDB', err));

app.listen(3000, () => {
console.log('Server is running on port 3000');
});

This code sets up a basic Express JS server and connects to a local MongoDB database called myapp. You can customize the database URL according to your requirements.

Step 3: Test the Connection

To test the connection to MongoDB, run the following command in the terminal:

node app.js

If the connection is successful, you should see the message ‘Connected to MongoDB’ in the console. You can also use a MongoDB client to verify that the connection has been established.

Conclusion

In this tutorial, we learned how to create a server-side web app using Node JS and Express JS, and how to connect to a MongoDB database. By following these steps, you can start building powerful and scalable web applications with ease.

0 0 votes
Article Rating
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@simrananand646
6 months ago

Subscribe to get notified for interesting videos: https://www.youtube.com/channel/UCHNkA15KHRoljTA2qhwwDEA?sub_confirmation=1

@saaraanand956
6 months ago

Really helpful video 👌👍👍

@rohitanand5221
6 months ago

Great explanation!