Although MongoDB creates a collection automatically the first time you insert a document, calling db.createCollection() explicitly lets you attach JSON Schema validation rules, configure capped collections, or create unique indexes before traffic hits your app.
Adding $jsonSchema rules inside createCollection() forces MongoDB to reject malformed documents—like a users record missing an email—even if multiple services write to the same database. Pairing that with createIndex({ email: 1 }, { unique: true }) guarantees uniqueness at the database level.
import { MongoClient } from 'mongodb';
const client = new MongoClient(process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017');
async function setupUsersCollection() {
try {
await client.connect();
const db = client.db('kodersolution_store');
const existing = await db.listCollections({ name: 'users' }).toArray();
if (existing.length === 0) {
await db.createCollection('users', {
validator: {
$jsonSchema: {
bsonType: 'object',
required: ['email', 'fullName'],
properties: {
email: { bsonType: 'string' },
fullName: { bsonType: 'string' },
},
},
},
});
}
await db.collection('users').createIndex({ email: 1 }, { unique: true });
console.log('Users collection and unique email index verified.');
} finally {
await client.close();
}
}
setupUsersCollection().catch((err) => console.error('Collection setup error:', err.message));
For fixed-size circular logs, capped: true with size and max keeps disk usage bounded automatically. For IoT metrics or clickstream analytics, { timeseries: { timeField: 'timestamp' } } optimizes storage and date-range queries.
createCollection() unconditionally on startup without checking: Creating an existing collection throws NamespaceExists (code 48). Always inspect listCollections({ name }) first or handle error code 48.createIndex({ email: 1 }, { unique: true }) fails with E11000 if duplicate emails are already in the collection. Create indexes during initial setup.insertOne and updateOne writes and consumes RAM. Index only fields queried or sorted frequently.db.createCollection() required before calling insertOne()?No. db.collection('orders').insertOne(...) creates the 'orders' collection automatically if it does not exist yet.
Call await db.collection('temp_logs').drop(), checking first that it exists or catching NamespaceNotFound.
createIndex() block if the index already exists with the same options?No. createIndex() is idempotent—if the identical index already exists, MongoDB returns its name immediately without rebuilding it.
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.