How To connect mongoDB database with Node js

How To connect mongoDB database with Node js
596 Views

In the rapidly evolving world of web development, mastering the art of database connectivity is crucial. MongoDB, a leading NoSQL database, combined with Node.js, a powerful JavaScript runtime, forms a robust backend foundation.

This guide will walk you through how to connect MongoDB with Node.js, ensuring a smooth and efficient database connection process. With CodexCoach, you will not only learn the basics but also adopt best practices that set you apart in the web development service.

Install Library in Your Project

Before diving into the code, the first step to connect Node to MongoDB is installing the necessary library in your project. MongoDB’s official Node.js driver allows your application to interact with your database seamlessly. Here’s how to get started:

  1. Open your terminal or command prompt.
  2. Navigate to your project directory.
  3. Run the following command to install the MongoDB driver:
- npm install express dotenv nodemon

Create server.js File

With the library installed, the next step is to create a server.js file where you’ll set up your server and establish the MongoDB connection. Here’s a simple example to get you started:

  1. In your project directory, create a file named server.js.
  2. Open server.js in your preferred code editor.
  3. Add the following code to connect to MongoDB:
const express = require("express");
const mongoose = require("mongoose");

require("dotenv").config();

const PORT = process.env.PORT;
const MONGODB_URI= process.env.MONGODB_URI;
const dbPassword = process.env.DB_PASSWORD;
const dbHost = process.env.DB_HOST;

const MONGODB_URI =MONGODB_URI

const app = express();

app.get("/", (req, res) => {
 console.log(req);
 res.status(200).send("hello welcome!");
});

mongoose
 .connect(MONGODB_URI)
 .then(() => {
   app.listen(PORT, () => {
     console.log("Database Connected...!");
     console.log(`Server started at http://localhost:${PORT}`);
   });
 })
 .catch((err) => {
   console.log(err);
 });

Also read: How To connect mySQL database with Node js

Create .env File

Hardcoding your database URI and other sensitive information in your server.js file is not a good practice. Instead, you should use an environment file (.env) to securely store your configuration details. Here’s how to set it up:

  1. Create a .env file in your project root.
  2. Add your MongoDB URI like so:
PORT = 3000
MONGODB_URI=your_mongodb_connection_string_here

Remember to install the dotenv package by running npm install dotenv if you haven’t already. This modification ensures your mongodb connection node js is both secure and scalable.

Download Demo from Here

To solidify your understanding and give you a head-start, CodexCoach provides a downloadable demo project. This project encapsulates all the steps covered and showcases best practices in action.

Download the demo here to explore a fully functional setup where you can connect to MongoDB from Node.js effortlessly.

By following this guide, you’re now equipped with the knowledge to establish a mongodb connection in node.js effectively. Whether you’re working on a personal project or a large-scale application, these steps form the backbone of a robust backend architecture.

Remember, the key to mastering database connectivity is practice and continuous learning. Explore more, build more, and make your mark in the world of web development with CodexCoach leading the way.

Was this article helpful?
YesNo

Leave a comment

Your email address will not be published. Required fields are marked *