KoderSolutionKoderSolution LogoKoderSolution Logo
HomeArticlesTutorialsToolsRun CodeForumAI Lab
🟢

Node.js

Topic Hub & Articles

Node.js Intro

10 min

Node.js Get Started

10 min

Node.js Modules

10 min

Node.js HTTP Module

10 min

Node.js File System

10 min

Node.js URL Module

10 min

Node.js NPM

10 min

Node.js Events

10 min

Node.js Upload Files

10 min

Node.js Email

10 min

Node.js Buffer

10 min

Recap Quiz

Gated

Milestone Assessment

Node.js Streams

10 min

Node.js Crypto

10 min

Node.js OS Module

10 min

Node.js Path Module

10 min

Node.js Global Objects

10 min

Recap Quiz

Gated

Milestone Assessment

Node.js Process

10 min

Node.js Child Processes

10 min

Node.js Worker Threads

10 min

Node.js DNS Module

10 min

Node.js Query String

10 min

Recap Quiz

Gated

Milestone Assessment

MySQL Connect

10 min

MySQL Create Database

10 min

Recap Quiz

Gated

Milestone Assessment

Node.js MySQL ORDER BY Clause

10 min

Recap Quiz

Gated

Milestone Assessment

MongoDB Intro

10 min

MongoDB Create Database

10 min

MongoDB Create Collection

10 min

MongoDB Insert

10 min

Recap Quiz

Gated

Milestone Assessment

MongoDB Find

10 min

MongoDB Query

10 min

MongoDB Sort

10 min

MongoDB Delete

10 min

MongoDB Update

10 min

Recap Quiz

Gated

Milestone Assessment

MongoDB Limit

10 min

MongoDB Join

10 min

Progress
0%

0 / 35 Lessons

KoderSolutionKoderSolution LogoKoderSolution Logo

The world’s most advanced technical ecosystem for modern software engineers. Learn, build, and grow with next-generation developer tools and resources.

Facebook PageX (Twitter) ProfileYouTube ChannelContact Support

Engineering Newsletter

Subscribe for weekly software engineering tutorials, architecture guides, and developer tool updates.

Platforms

  • Technical Articles
  • Interactive Tutorials
  • AI Coding Lab
  • Developer Forum
  • Developer Tools

Pages

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of Service
  • Refund Policy
  • Disclaimer
  • Advertisement

Popular Topics

  • PHP
  • Laravel
  • Python
  • React.Js
  • MySQL
© 2026 KoderSolutionAll Rights Reserved
Developed Bymaksudur.dev
Node.jsNode.js MongoDB
Lesson

MongoDB Create Database

10 min reading
Free Course

MongoDB Create Database in Node.js: How Lazy Creation Works

In MongoDB, calling client.db('shop_db') does not immediately write anything to disk. MongoDB creates a database automatically—lazily—the very first time you create a collection or insert at least one document into it.

Initializing a Database by Inserting an Initial Document

If you inspect admin.listDatabases() right after calling client.db('shop_db'), the new database will not appear yet. Once you run insertOne() on a collection inside shop_db, MongoDB materializes both the database and the collection together.

flowchart LR
    A["client.db('shop_db')"] --> B["Database Handle Only (Not on Disk Yet)"]
    B --> C["collection.insertOne(doc)"]
    C --> D["MongoDB Creates Database & Collection on Disk"]
import { MongoClient } from 'mongodb';

const uri = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri);

async function initDatabase() {
  try {
    await client.connect();
    const db = client.db('kodersolution_store');
    const settings = db.collection('settings');

    // Database is materialized on disk once a document is stored
    const result = await settings.updateOne(
      { key: 'site_config' },
      { $setOnInsert: { key: 'site_config', currency: 'USD', createdAt: new Date() } },
      { upsert: true }
    );

    const adminInfo = await db.admin().listDatabases();
    const exists = adminInfo.databases.some((d) => d.name === 'kodersolution_store');
    console.log('Database initialized:', exists, 'Upserted:', result.upsertedCount);
  } finally {
    await client.close();
  }
}

initDatabase().catch((err) => console.error('Init failed:', err.message));

Naming Rules and Idempotent Bootstrap Scripts

MongoDB database names are case-sensitive on most platforms and cannot contain /, \, ., spaces, or $, and must stay under 64 characters. Using updateOne(..., { upsert: true }) with $setOnInsert makes setup scripts safe to run repeatedly without creating duplicate starter records.

Common Mistakes to Avoid

  • Assuming client.db('name') failed because show dbs looks empty: An empty database without collections or documents never shows up in listDatabases(). Insert a document or run createCollection() first.
  • Using hyphens inconsistently or uppercase letters across environments: Stick to lowercase snake_case database names (like koder_store) so Linux and Windows/macOS servers never conflict.
  • Hardcoding mongodb:// credentials in source code: Always read process.env.MONGODB_URI so Atlas or production connection strings stay outside Git.

Frequently Asked Questions

What does db.dropDatabase() do?

await db.dropDatabase() permanently deletes the selected database and all its collections and indexes—use it only in automated test cleanup or intentional teardown scripts.

Can one MongoClient access multiple databases on the same cluster?

Yes. Calling client.db('analytics') and client.db('billing') shares the exact same underlying connection pool.

Why use $setOnInsert with upsert: true?

$setOnInsert sets fields only when inserting a brand-new document and leaves an existing document untouched if it already exists.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground

Related Developer Tools & Topic Hub

Node.js Topic Hub
JSON Formatter
Validate, format, and minify JSON
Regex Tester
Test regular expression patterns
JWT Decoder
Inspect JSON Web Token payloads
All Node.js Articles
Deep-dive guides, tips & discussions
PreviousMongoDB Intro
Continue JourneyNext: MongoDB Create Collection

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum