Node.js MongoDB Create Database
π Node.js MongoDB β Create Database
Weβll cover both MongoDB native driver and Mongoose.
β 1. Install MongoDB Driver or Mongoose
β 2. Using Native MongoDB Driver
Key points:
-
client.db("mydb")references the database. -
Database doesnβt exist until you insert a document.
-
Collection
usersis also created automatically when inserting.
β 3. Using Mongoose
Key points:
-
mongoose.connect("mongodb://localhost:27017/mydb")references the database. -
Database
mydbis created automatically when the first document is inserted. -
Collections are created automatically by Mongoose models.
β 4. Tips & Best Practices
-
MongoDB databases are lazy-created β they exist only after inserting data.
-
Always define schemas with Mongoose for consistent documents.
-
Use meaningful database and collection names.
-
For production, use connection pooling to improve performance.
