Skip to content

Latest commit

 

History

History
229 lines (186 loc) · 5.41 KB

File metadata and controls

229 lines (186 loc) · 5.41 KB

MongoDB Starter Pack

Step 1: Prerequisites

  • Node.js installed (v14 or higher)
  • MongoDB Atlas account (free) OR Docker installed

Step 2: Navigate to MongoDB Folder & Install

cd mongodb/
npm install

Step 3: Configure Database

Choose ONE option:

Option A: MongoDB Atlas (Recommended - No installation needed)

  1. Go to MongoDB Atlas
  2. Create a free account and cluster
  3. Click "Connect" → "Connect your application"
  4. Copy the connection string
  5. Create .env file:
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/hackathon?retryWrites=true&w=majority
PORT=3000

Option B: Local Docker

# Start MongoDB container
docker run -d -p 27017:27017 --name mongodb-hackathon mongo:latest

# Create .env file
echo "MONGODB_URI=mongodb://localhost:27017/hackathon" > .env
echo "PORT=3000" >> .env

Step 4: Test Connection (Optional)

npm run test-connection

You should see:

 MongoDB Connected Successfully!
 Database: hackathon
 Connection String: mongodb://...

Step 5: Seed Sample Data

npm run seed

Step 6: Start the Server

npm start

Server runs at: http://localhost:3000

Project Structure

mongodb/
├── package.json             # Dependencies
├── .env.example             # Environment template
├── .env                     # Your config (create this!)
├── .gitignore               # Git ignore file
├── MongoDB_Starter.md       # This file
├── src/
│   ├── server.js           # Express server setup
│   ├── config/
│   │   └── database.js     # MongoDB connection
│   ├── models/             # Mongoose schemas
│   │   ├── User.js
│   │   └── Project.js
│   ├── routes/             # API endpoints
│   │   ├── users.js
│   │   └── projects.js
│   ├── controllers/        # Business logic
│   │   ├── userController.js
│   │   └── projectController.js
│   └── middleware/         # Custom middleware
│       └── errorHandler.js
├── scripts/
│   └── seed.js             # Sample data seeder
└── tests/
    ├── testConnection.js   # Connection test
    └── api.test.js         # Basic API tests

API Endpoints

Once running, test these endpoints:

Users

  • GET /api/users - Get all users
  • GET /api/users/:id - Get user by ID
  • POST /api/users - Create new user
  • PUT /api/users/:id - Update user
  • DELETE /api/users/:id - Delete user

Projects

  • GET /api/projects - Get all projects
  • GET /api/projects/:id - Get project by ID
  • GET /api/projects/user/:userId - Get projects by user
  • POST /api/projects - Create new project
  • PUT /api/projects/:id - Update project
  • DELETE /api/projects/:id - Delete project

Example API Usage

Create a User

curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{
    "username": "johndoe",
    "email": "john@example.com",
    "fullName": "John Doe"
  }'

Create a Project

curl -X POST http://localhost:3000/api/projects \
  -H "Content-Type: application/json" \
  -d '{
    "title": "My Hackathon Project",
    "description": "Building something awesome!",
    "userId": "USER_ID_FROM_ABOVE",
    "technologies": ["mongodb", "node.js", "react"]
  }'

Get All Projects

curl http://localhost:3000/api/projects

Customization Guide

Adding a New Model

  1. Create model file in src/models/:
// src/models/Team.js
const mongoose = require('mongoose');

const teamSchema = new mongoose.Schema({
  name: { type: String, required: true },
  members: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
  createdAt: { type: Date, default: Date.now }
});

module.exports = mongoose.model('Team', teamSchema);
  1. Create routes file in src/routes/:
// src/routes/teams.js
const express = require('express');
const router = express.Router();
const Team = require('../models/Team');

router.get('/', async (req, res) => {
  const teams = await Team.find().populate('members');
  res.json(teams);
});

module.exports = router;
  1. Register routes in src/server.js:
const teamRoutes = require('./routes/teams');
app.use('/api/teams', teamRoutes);

Troubleshooting

Connection Failed

# Test your connection
npm run test-connection

# Check your .env file
cat .env

Common issues:

  • Check your .env file exists and has correct MongoDB URI
  • Verify MongoDB Atlas IP whitelist (set to 0.0.0.0/0 for development)
  • Ensure MongoDB service is running (if using Docker/local)
  • Check if username/password contains special characters (URL encode them)

Port Already in Use

# Change PORT in .env file to another port (e.g., 3001)
PORT=3001

Seed Data Issues

# Clear database and re-seed
npm run seed:fresh

Deployment (Optional)

Deploy to Heroku

# Install Heroku CLI, then:
heroku create your-app-name
heroku config:set MONGODB_URI=your_atlas_connection_string
git push heroku main

Deploy to Vercel/Netlify

  • Use MongoDB Atlas for database
  • Set environment variables in platform settings

Learn More