Connect node with mongodb | mongodb npm

Connect MongoDB with Node.js


Install MongoDB NPM Package

Before connecting MongoDB with Node.js, you need to install a package. You can use either:

  1. mongodb (official native driver)
  2. or mongoose (ODM library – Object Document Mapper)


Install Command:

npm i mongodb


Verify the Installation

After installing, check your package.json file.

It should show:

"dependencies": {
"mongodb": "^<version>"
}

This means the package is successfully installed.


MongoDB Should Be Running

Important: Before connecting, ensure MongoDB is running locally on your system.

You can start MongoDB using this command (for macOS users with Homebrew):

brew services start mongodb-community@8.0

Once MongoDB is running, we can connect to it using our Node.js code.


Define DB Name and URL

Before writing the logic, define:

  1. Database Name (e.g., school)
  2. MongoDB URL (default is mongodb://localhost:27017)


Create Server and Connect MongoDB

import express from "express";
import { MongoClient } from "mongodb";

// Define DB name and MongoDB URL
const dbName = "school";
const url = "mongodb://localhost:27017";

// Create MongoDB client
const client = new MongoClient(url);

// Create async function for DB connection
async function dbConnection() {
await client.connect(); // connect to MongoDB
const db = client.db(dbName); // select the database
const collection = db.collection("students"); // get collection

const result = await collection.find().toArray(); // get all data

console.log(result); // log result
}

// Call connection function
dbConnection();

// Create express app
const app = express();


Code Does

  1. Connects your Node.js app to MongoDB.
  2. Accesses a database called school.
  3. Fetches all documents from the students collection.
  4. Logs the result in the terminal.