Node.js Tutorial
Estimated reading: 3 minutes 272 views

Node.js โ€“ MongoDB: Introduction & Setup โ€“ Connect and Create NoSQL Databases

Introduction โ€“ Why Use MongoDB with Node.js?

MongoDB is a flexible, document-oriented NoSQL database that stores data in JSON-like structures. Combined with Node.js, it becomes a powerful backend stack for scalable and modern web applicationsโ€”ideal for REST APIs, real-time apps, and data-driven UIs.

In this guide, youโ€™ll learn:

  • How to install and set up MongoDB for Node.js
  • How to use the official MongoDB Node.js driver
  • How to create a database and collections programmatically

Topics Covered

Topic Description
Node.js โ€“ MongoDB Get StartedInstall MongoDB locally/cloud & connect via Node.js
Node.js โ€“ MongoDB Create Database / CollectionsCreate new databases and collections dynamically from your code

Node.js โ€“ MongoDB Get Started

Prerequisites

Youโ€™ll need:

  • Node.js installed (node -v)
  • MongoDB installed locally OR a cloud account (MongoDB Atlas)
  • A project directory with npm init -y run

Step 1: Install MongoDB Driver

npm install mongodb

This installs the official mongodb Node.js driver.


Step 2: Connect to MongoDB

Create db.js:

const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017'; // For Atlas, use the full connection string

const client = new MongoClient(uri);

async function connectDB() {
  try {
    await client.connect();
    console.log('MongoDB Connected!');
  } catch (err) {
    console.error('Connection failed:', err);
  }
}

connectDB();

module.exports = client;

Output:

MongoDB Connected!

Replace localhost with Atlas URI if using the cloud version.


Node.js โ€“ MongoDB Create Database / Collections

Step 3: Create Database & Collection

Create createCollection.js:

const client = require('./db');

async function createCollection() {
  const db = client.db('myCompany');
  await db.createCollection('employees');
  console.log('Collection created!');
}

createCollection();

Output:

Collection created!

MongoDB auto-creates the database (myCompany) and collection (employees) on first insert.


Step 4: Insert Sample Document

async function insertSample() {
  const db = client.db('myCompany');
  const result = await db.collection('employees').insertOne({
    name: "Alice",
    position: "HR",
    salary: 50000
  });
  console.log("Document ID:", result.insertedId);
}

insertSample();

Output:

Document ID: 64aefb1b48ef47e344d9a123

No need to define schema in MongoDB. Documents are flexible and dynamic.


Summary โ€“ Recap & Next Steps

MongoDB is a schema-less, document-based database that fits perfectly with the asynchronous nature of Node.js. You can quickly connect, create databases/collections, and start inserting dataโ€”all with just a few lines of code.

Key Takeaways:

  • Use the mongodb driver to connect to MongoDB from Node.js
  • db.createCollection() defines a collection inside a database
  • Documents are inserted as plain JavaScript objects
  • MongoDB is ideal for JSON-style, nested, and flexible data storage

Real-World Uses:

  • Building RESTful APIs (users, posts, orders, products)
  • Saving chat logs or activity streams
  • Managing flexible form submissions and IoT data

Frequently Asked Questions

Can I use MongoDB without installing it locally?
Yes, use MongoDB Atlas โ€“ a cloud-hosted version with free tiers.


How do I create a database in MongoDB?
Just reference it via client.db('name'). MongoDB will create it when you write to it.


Is MongoDB schema-less?
Yes. Collections can store documents with varying structures, making it highly flexible.


How do I secure my MongoDB connection?
Use .env files to store your URI and use authentication with TLS for production.


Share Now :
Share

๐Ÿ“‚ Node.js โ€“ MongoDB: Introduction & Setup

Or Copy Link

CONTENTS
Scroll to Top