How to connect MongoDB with NodeJS?
Whether you have a technical background or not you have definitely “heard” about MongoDB and NodeJS. These terms are very popular mainly in the technical world. From whichever background you belong to whether technical or non-technical maybe you are stuck in connecting MongoDB with NodeJS. No worries you have got the best place where you will get the simple steps on how to connect MongoDB with NodeJS.
To start with, if you know a bit about how web servers work, you know that Node.js and MongoDB are both important for the backend of a website. Node.js helps build the server, and MongoDB is a type of database used to store data. In this guide, we will focus on how to connect MongoDB with Node.js so that your server can store and manage data efficiently. Let’s get started!
STEP 1: Install MongoDB
- Ensure MongoDB is installed and running on your local machine or accessible through a cloud service like MongoDB Atlas.
Here are the 2 Processes:
- Install Mongodb Local machine
- Use Mongodb Cloud database
For installing Mongodb in Local machine
Step 1 :Go to the official website
- Download Mongodb community server (Ref : Download MongoDB Community Server | MongoDB)
Step 2: We can Access Mongodb database under two method
METHOD 1: CUI [ Character User Interface]
We have to download mongoshell [It is a MongoDB Command Line Database Tool] for accessing mongodb database locally. (Ref : Download MongoDB Command Line Database Tools | MongoDB)
METHOD 2: GUI [Graphical User Interface]
By Installing MongoDB Compass (Ref : https://www.mongodb.com/products/tools/compass)
Use MongoDB Cloud Database (I.e. MongoDB Atlas)
- First signup the Official MongoDB Atlas database
- Then create a cluster that we can choose from the Free Altas server
- After that create the database
- In the Database section, we can find the MongoDB Atlas Cloud database connection string. We need to use this connection URL to manipulate the database
STEP 2: Set Up Your Development Environment
- Install Node.js and npm:
Ensure you have Node.js version 12 or later and npm installed. You can check the versions using node –version and npm –version.
STEP 3: Create a New Project
- Create a directory for your project
Use mkdir your-project-name and then navigate into it with cd your-project-name.
- Initialize your project
Run npm init -y to create a package.json file with default values.
STEP 4: Install the MongoDB Node.js Driver
- Install the MongoDB driver:
Use the command npm install mongodb@4.1 to download the MongoDB package and its dependencies.
STEP 5: Create a MongoDB Database
- Create a MongoDB cluster
You can create a free tier cluster on MongoDB Atlas or use a local MongoDB instance. For MongoDB Atlas, follow the guide to set up a new cluster and load sample data.
- Retrieve the connection string
Log into your Atlas account, navigate to the Database section, and copy the connection string for your cluster.
STEP 6: Connect to Your MongoDB Cluster
- Create a configuration file ( which is optional for you):
You can store your connection string in a .env file to keep it separate from your code. Install dotenv using npm install dotenv to load this configuration.
- Create a Node.js application file:
Create a file named index.js in your project directory.
- Import the MongoDB driver and connect:
Use the following code to connect to your MongoDB cluster:
const { MongoClient } = require(“mongodb”);
const uri = “mongodb+srv://<user>:<password>@<cluster-url>
retryWrites=true&writeConcern=majority”;
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const database = client.db(‘your-database-name’);
const collection = database.collection(‘your-collection-name’);
// Perform your database operations here
} finally {
await client.close();
}
}
run().catch(console.dir);
“`.
STEP 7: Run Your Node.js Application
Execute the application:
Run your Node.js application using node index.js from the command line.
Additional Notes
- Local MongoDB Connection: If connecting to a local MongoDB instance, ensure it is running and use the appropriate connection string (e.g., mongodb://localhost:27017or mongodb://127.0.0.1:27017 for IPv6 compatibility).
- CRUD Operations: Once connected, you can perform CRUD (Create, Read, Update, Delete) operations using the MongoDB driver’s methods.
By following these steps, you can successfully connect a Node.js application to a MongoDB. But as you are just starting your career, the best way you can learn is under the guidance of experienced mentors. With the assistance full stack development course, you can master the field you are interested in. And let’s be honest in the IT field there is no place for someone who’s average! You need to master each and every aspect of programming! All the best!