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.
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));
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.
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.snake_case database names (like koder_store) so Linux and Windows/macOS servers never conflict.mongodb:// credentials in source code: Always read process.env.MONGODB_URI so Atlas or production connection strings stay outside Git.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.
MongoClient access multiple databases on the same cluster?Yes. Calling client.db('analytics') and client.db('billing') shares the exact same underlying connection pool.
$setOnInsert with upsert: true?$setOnInsert sets fields only when inserting a brand-new document and leaves an existing document untouched if it already exists.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.