Node.js Tutorial
Estimated reading: 3 minutes 105 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