MongoDB Create Database
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 becauseshow dbslooks empty: An empty database without collections or documents never shows up inlistDatabases(). Insert a document or runcreateCollection()first. - Using hyphens inconsistently or uppercase letters across environments: Stick to lowercase
snake_casedatabase names (likekoder_store) so Linux and Windows/macOS servers never conflict. - Hardcoding
mongodb://credentials in source code: Always readprocess.env.MONGODB_URIso 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.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.