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

npm install mongodb
# or
npm install mongoose

βœ… 2. Using Native MongoDB Driver


 

Key points:

  • client.db("mydb") references the database.

  • Database doesn’t exist until you insert a document.

  • Collection users is also created automatically when inserting.


βœ… 3. Using Mongoose


 

Key points:

  • mongoose.connect("mongodb://localhost:27017/mydb") references the database.

  • Database mydb is 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.

You may also like...