Node.js MongoDB Create Collection
🚀 Node.js MongoDB – Create Collection
In MongoDB, collections are like tables in SQL.
Collections are automatically created when you insert the first document.
You can also explicitly create a collection if needed.
We’ll cover both approaches.
1. Install MongoDB Driver or Mongoose
2. Using MongoDB Native Driver
Explicitly Create a Collection
Notes:
db.createCollection("users")explicitly creates the collection.If you insert a document without creating a collection, MongoDB will create it automatically.
Automatic Collection Creation
3. Using Mongoose
With Mongoose, collections are created automatically based on models.
Notes:
Mongoose automatically pluralizes the model name to create the collection (
User→users).Collections are created only when a document is inserted.
4. Tips & Best Practices
Use explicit collection creation if you want to define options like
capped,size, orvalidation.For production, prefer Mongoose models for consistent schema management.
Avoid inserting documents directly in unstructured collections unless you really need dynamic schema.
Always close the connection after operations.
