This guide explains how to set up MongoDB for the ApniDukaan e-commerce platform with proper data structure and seeding.
- MongoDB Atlas account (recommended) or local MongoDB installation
- Node.js installed
- Environment variables configured
- Go to MongoDB Atlas
- Sign up for a free account
- Create a new cluster (M0 Sandbox is free)
- Click "Connect" on your cluster
- Choose "Connect your application"
- Copy the connection string
- Replace
<password>with your database user password
# In your .env file
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/apnidukaan?retryWrites=true&w=majority# Windows (using Chocolatey)
choco install mongodb
# macOS (using Homebrew)
brew install mongodb-community
# Ubuntu/Debian
sudo apt-get install mongodb# Windows
net start MongoDB
# macOS/Linux
sudo systemctl start mongod
# or
mongod --config /usr/local/etc/mongod.conf# In your .env file
MONGODB_URI=mongodb://localhost:27017/apnidukaanapnidukaan/
├── products/ # Product catalog
├── categories/ # Product categories
├── users/ # User accounts
├── orders/ # Order history
├── cart/ # Shopping cart (Redis)
└── sessions/ # User sessions (Redis)
{
_id: ObjectId,
name: String, // Product name
price: Number, // Current price
originalPrice: Number, // Original price
discount: Number, // Discount percentage
rating: Number, // Average rating (1-5)
reviews: Number, // Number of reviews
images: [String], // Product images array
category: String, // Main category
subcategory: String, // Subcategory
brand: String, // Brand name
description: String, // Product description
specifications: Object, // Technical specs
inStock: Boolean, // Availability
stockQuantity: Number, // Stock count
tags: [String], // Search tags
createdAt: Date, // Creation date
updatedAt: Date // Last update
}{
_id: ObjectId,
name: String, // Category name
slug: String, // URL-friendly name
description: String, // Category description
image: String, // Category image
parentCategory: ObjectId, // Parent category (for subcategories)
isActive: Boolean, // Active status
sortOrder: Number // Display order
}{
_id: ObjectId,
email: String, // User email (unique)
password: String, // Hashed password
firstName: String, // First name
lastName: String, // Last name
phone: String, // Phone number
addresses: [Object], // Shipping addresses
role: String, // User role (user/admin)
isActive: Boolean, // Account status
createdAt: Date, // Registration date
updatedAt: Date // Last update
}{
_id: ObjectId,
userId: ObjectId, // User reference
orderNumber: String, // Unique order number
items: [Object], // Order items
totalAmount: Number, // Total order amount
status: String, // Order status
paymentMethod: String, // Payment method used
paymentStatus: String, // Payment status
shippingAddress: Object, // Delivery address
trackingNumber: String, // Shipping tracking
createdAt: Date, // Order date
updatedAt: Date // Last update
}# Navigate to project root
cd /path/to/apnidukaan-ecommerce
# Install dependencies (if not already done)
npm install
# Run the seeding script
node scripts/seed-database.js- 5 Categories: Electronics, Fashion, Home & Garden, Sports, Books
- 5 Sample Products: Headphones, Smartwatch, Backpack, Camera, Shoes
- Database Indexes: For optimal query performance
- Sample Data: Ready for testing
# Check if data was inserted
# You can use MongoDB Compass or Atlas UI to verifyThe API Gateway automatically detects MongoDB connection and uses real data when available, falls back to mock data when MongoDB is unavailable.
# Backend (.env)
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/apnidukaan
REDIS_URL=redis://default:password@redis-cloud-url:port
# Frontend (.env.local)
NEXT_PUBLIC_API_URL=https://your-api-gateway-url.comThe seeding script automatically creates these indexes for optimal performance:
{ category: 1 }- Category filtering{ name: "text", description: "text" }- Text search{ price: 1 }- Price sorting{ rating: -1 }- Rating sorting
{ slug: 1 }- Category lookup by slug
{ email: 1 }- Unique email constraint
{ userId: 1 }- User order lookup{ createdAt: -1 }- Recent orders
Error: MongoDB connection failed
Solution: Check your MONGODB_URI in .env file
Error: Authentication failed
Solution: Verify username/password in connection string
Error: Server selection timed out
Solution: Check your IP whitelist in MongoDB Atlas
Error: Database does not exist
Solution: The database will be created automatically on first write
# Enable debug logging
DEBUG=mongodb:* node scripts/seed-database.js// Use the API endpoint
POST /api/catalog/products
{
"name": "New Product",
"price": 999,
"category": "electronics",
// ... other fields
}// Use the API endpoint
PUT /api/catalog/products/:id
{
"price": 899,
"stockQuantity": 50
}// Use MongoDB directly for bulk operations
const products = await db.collection('products').insertMany([
{ name: 'Product 1', price: 100 },
{ name: 'Product 2', price: 200 }
]);The MongoDB driver automatically handles connection pooling.
- Use indexes for filtering and sorting
- Limit results with pagination
- Use projection to select only needed fields
- Redis is used for session storage
- Product data can be cached for better performance
- Use strong passwords
- Enable IP whitelisting
- Use MongoDB Atlas security features
- Validate all input data
- Use MongoDB schema validation
- Sanitize user inputs
- Enable automatic backups in MongoDB Atlas
- Test restore procedures regularly
- Run the seeding script to populate your database
- Test the API endpoints to ensure data is being served
- Add more products through the admin interface
- Monitor performance and optimize as needed
- Set up regular backups for production
If you encounter issues:
- Check the troubleshooting section above
- Verify your environment variables
- Test MongoDB connection independently
- Check the application logs for detailed error messages
Ready to seed your database? Run:
node scripts/seed-database.js