Connect to MongoDB using Mongoose

📌 What: MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. Mongoose is an ODM (Object Data Modeling) library for Node.js that simplifies interactions with MongoDB.

🎯 Why: To store and retrieve structured data such as users, products, or bookings in an organized, schema-based way that supports validation and middleware.

⚙️ How:

// db.js (MongoDB connection) const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true, useUnifiedTopology: true, }) .then(() => console.log("✅ MongoDB Connected")) .catch(err => console.error("❌ Connection Error", err)); // user.model.js (Schema & Model) const userSchema = new mongoose.Schema({ name: String, email: { type: String, required: true, unique: true }, password: String }); const User = mongoose.model("User", userSchema); module.exports = User;

🕐 When: Use Mongoose whenever your app needs to persist structured data — such as user details, messages, or inventory — in a MongoDB database.

💡 Tip: Use MongoDB Atlas for cloud-based databases and environment variables to secure your DB URI in production (.env).