# Database Commands Guide

## Overview

Your application now has **three separate database commands**:

| Command | Script | Purpose | Use Case |
|---------|--------|---------|----------|
| `pnpm db:reset` | `scripts/reset.mjs` | Drop all collections | Clean slate |
| `pnpm db:seed` | `scripts/seed.mjs` | Populate with demo data | Add data |
| `pnpm db:full-reset` | Both scripts | Reset + seed | Complete rebuild |

---

## Command Details

### 1. Reset Database

```bash
pnpm db:reset
```

**What it does:**
- Connects to MongoDB
- Drops ALL collections (users, products, orders, etc.)
- Shows progress for each collection cleared
- Disconnects from MongoDB

**Output example:**
```
✓ Connected to MongoDB

🗑️  Starting database reset...

   ✓ Cleared user (8 documents)
   ✓ Cleared account (8 documents)
   ✓ Cleared customerprofiles (3 documents)
   ✓ Cleared adminprofiles (1 documents)
   ✓ Cleared staffprofiles (1 documents)
   ✓ Cleared vendors (3 documents)
   ✓ Cleared categories (8 documents)
   ✓ Cleared products (21 documents)
   ✓ Cleared collections (4 documents)
   ✓ Cleared orders (20 documents)
   ✓ Cleared reviews (7 documents)
   ✓ Cleared wishlists (3 documents)
   ✓ Cleared coupons (4 documents)
   ✓ Cleared inventorylocations (3 documents)
   ✓ Cleared blogposts (3 documents)
   ✓ Cleared blogcategories (3 documents)
   ✓ Cleared menus (5 documents)
   ✓ Cleared notifications (7 documents)
   ✓ Cleared settings (1 documents)
   ✓ Cleared counters (2 documents)

✅ Database reset completed successfully!
```

**Use when:**
- You want to start fresh
- After pulling new seed changes
- Development environment cleanup
- Fixing corrupted data

---

### 2. Seed Database

```bash
pnpm db:seed
```

**What it does:**
- Checks for existing data
- Only creates data that doesn't exist
- Safe to run multiple times
- Shows progress for each entity type

**Output example:**
```
✓ Connected to MongoDB

👤 Creating admin...
   ✓ Created admin: admin@storify.com / Admin@123

🏪 Creating vendors...
   ✓ Created vendor: vendor@storify.com / Vendor@123
   ✓ Created vendor: vendor2@example.com / vendor123
   ✓ Created vendor: vendor3@example.com / vendor123

👥 Creating customers...
   ✓ Created customer: customer@storify.com / Customer@123
   ...

📦 Creating products...
   ✓ Created product: iPhone 15 Pro Max
   ✓ Created product: iPhone 14 Pro
   ...

✅ Database seeded successfully!

============================================================
Demo Credentials:
============================================================
Admin:    admin@storify.com / Admin@123
Vendor:   vendor@storify.com / Vendor@123
Customer: customer@storify.com / Customer@123
Staff:    staff@storify.com / Staff@123
============================================================
```

**Use when:**
- Initial project setup
- Adding missing demo data
- Ensuring all seed entities exist
- Safe to run anytime (doesn't overwrite existing data)

---

### 3. Full Reset (Reset + Seed)

```bash
pnpm db:full-reset
```

**What it does:**
- Runs `db:reset` first
- Then runs `db:seed`
- Complete database rebuild

**Equivalent to:**
```bash
pnpm db:reset && pnpm db:seed
```

**Use when:**
- Fresh start after major schema changes
- Complete database rebuild
- CI/CD deployment
- Starting development after pulling major updates

---

## Workflows

### Initial Setup

```bash
# Clone repository
git clone <repo-url>
cd storify

# Install dependencies
pnpm install

# Reset and seed database
pnpm db:full-reset

# Start development
pnpm dev
```

### Regular Development

```bash
# Option 1: Seed only (safe, keeps existing data)
pnpm db:seed

# Option 2: Full reset (clears everything)
pnpm db:full-reset

# Start development
pnpm dev
```

### After Schema Changes

```bash
# Pull latest code
git pull origin main

# Clear and reseed with new schema
pnpm db:full-reset

# Test changes
pnpm dev
```

### Production Deployment

```bash
# NEVER run db:reset or db:full-reset on production!

# Only seed if needed (safe operation)
pnpm db:seed
```

---

## Data Seeded

### Entities Created

| Entity | Count | Description |
|--------|-------|-------------|
| **Admin Users** | 1 | Super admin account |
| **Vendors** | 3 | Tech Gadgets, Fashion Hub, Home Essentials |
| **Customers** | 3 | Demo customer accounts |
| **Staff** | 1 | Seller/POS staff account |
| **Categories** | 8 | Phone, Smart Watches, Cameras, etc. |
| **Products** | 21+ | Various tech and fashion items |
| **Orders** | 20 | Mix of online and POS orders |
| **Reviews** | 7+ | Product reviews with ratings |
| **Wishlists** | 3 | Customer wishlists |
| **Coupons** | 4 | Various discount types |
| **Collections** | 4 | Featured and seasonal |
| **Blog Posts** | 3 | Blog articles |
| **Menus** | 5 | Header and footer navigation |
| **Settings** | 1 | Complete store configuration |
| **Inventory Locations** | 3 | Warehouse and storefronts |
| **Notifications** | 7 | System notifications |

---

## Demo Credentials

### Default Accounts

```bash
Admin:
  Email:    admin@storify.com
  Password: Admin@123

Vendor:
  Email:    vendor@storify.com
  Password: Vendor@123

Customer:
  Email:    customer@storify.com
  Password: Customer@123

Staff:
  Email:    staff@storify.com
  Password: Staff@123

Additional Vendors:
  vendor2@example.com / vendor123
  vendor3@example.com / vendor123

Additional Customers:
  customer2@example.com / customer123
  customer3@example.com / customer123
```

---

## Environment Variables

Both commands require these environment variables:

```bash
# Required
MONGODB_URI=mongodb://localhost:27017/storify

# Optional
MONGODB_DB_NAME=storify
```

These are automatically loaded from `.env` file via `--env-file=.env` flag.

---

## Troubleshooting

### Command Not Found

```bash
# Check package.json scripts
cat package.json | grep '"db:'
```

### MongoDB Connection Error

```bash
# Ensure MongoDB is running
mongosh --eval "db.adminCommand('ping')"

# Check connection string
echo $MONGODB_URI
```

### Seed Fails

```bash
# Reset database first
pnpm db:reset

# Then seed
pnpm db:seed

# Check for errors
pnpm db:seed --verbose
```

### Permission Denied

```bash
# Check MongoDB user permissions
mongosh --eval "db.getUser('your-user')"
```

---

## Advanced Usage

### Seed with Custom Config

```bash
MONGODB_URI=mongodb://localhost:27017/test-db pnpm db:seed
```

### Dry Run (Preview)

```bash
# Not implemented yet, but you can check what would be created
node --dry-run scripts/seed.mjs
```

### Seed Specific Section

```bash
# Not implemented yet
node scripts/seed.mjs --section=products
```

---

## File Structure

```
scripts/
├── reset.mjs          # Database reset script (NEW)
├── seed.mjs          # Database seed script
├── create-admin.mjs   # Create admin utility
└── link-credential.mjs # Link credentials utility
```

---

## Safety Warnings

### ⚠️ NEVER DO THESE IN PRODUCTION

```bash
# DON'T reset production database
pnpm db:reset  # ❌ NEVER

# DON'T use full-reset
pnpm db:full-reset  # ❌ NEVER

# DON'T run in production without backup
pnpm db:seed  # ⚠️ BE CAREFUL
```

### ✅ SAFE OPERATIONS

```bash
# ALWAYS safe
pnpm db:seed  # ✅ Safe (doesn't overwrite existing data)

# ONLY in development
pnpm db:reset  # ✅ Safe in dev
pnpm db:full-reset  # ✅ Safe in dev
```

---

## Backup Before Reset

Always backup before running reset:

```bash
# MongoDB dump
mongodump --uri="mongodb://localhost:27017/storify" --out=./backup-$(date +%Y%m%d)

# Then reset
pnpm db:reset

# Restore if needed
mongorestore --uri="mongodb://localhost:27017/storify" ./backup-20260516
```

---

## Support

### Common Issues

**Issue: "Database already seeded"**
- This is normal! Seed is idempotent
- Only missing data will be created
- Safe to run multiple times

**Issue: "Reset not working"**
- Check MongoDB is running
- Verify connection string in `.env`
- Ensure you have write permissions

**Issue: "Lost demo data"**
- Run `pnpm db:seed` to recreate
- Check credentials are correct
- Verify database connection

---

## Summary

| Command | Action | Safety | Speed |
|---------|--------|--------|-------|
| `pnpm db:reset` | Drop all data | ⚠️ Use carefully | Fast |
| `pnpm db:seed` | Add missing data | ✅ Safe | Medium |
| `pnpm db:full-reset` | Complete rebuild | ⚠️ Use carefully | Medium |

**Best Practice:**
1. Use `db:seed` for regular development
2. Use `db:full-reset` after major changes
3. Never use either in production

---

Last Updated: 2026-05-16
