Skip to content

Instantly share code, notes, and snippets.

@decagondev
Created July 26, 2025 12:49
Show Gist options
  • Save decagondev/45cdeffbb54492c43880124df9038396 to your computer and use it in GitHub Desktop.
Save decagondev/45cdeffbb54492c43880124df9038396 to your computer and use it in GitHub Desktop.

Sprint 1: Database Operations Guide

Overview

This guide covers the first ticket of the BandersnatchStarter project, titled "Database Operations," as outlined in the repository: BandersnatchStarter/tickets/firstTicket.md. The objective of Sprint 1 is to set up a MongoDB database and populate it with "monster data" for use in a Flask-based web application. This guide is tailored for a junior JavaScript/TypeScript developer with about one year of experience, familiar with JavaScript concepts like Node.js, Express.js, and MongoDB (via Mongoose), but with limited Python exposure. The goal is to guide you toward a solution without providing complete code, helping you learn Python and MongoDB concepts by relating them to JavaScript equivalents.

Ticket Objectives

The first ticket focuses on:

  1. Setting up a MongoDB database: Create a MongoDB cluster and configure access.
  2. Connecting to MongoDB from Python: Use the pymongo library to establish a connection in your Flask app.
  3. Creating monster data: Insert sample monster data (e.g., name, strength, type) into the database.
  4. Basic database operations: Implement functionality to read and possibly update monster data.

This is similar to setting up a MongoDB database in a Node.js project, defining a schema with Mongoose, and creating CRUD (Create, Read, Update, Delete) endpoints in Express.js.

Prerequisites

Before starting, ensure you’ve followed the repository’s setup instructions:

  • Fork and clone the repository: git clone https://github.com/your-username/BandersnatchStarter.git.
  • Set up a Python virtual environment:
    • Windows: python -m venv venv and venv\Scripts\activate.
    • macOS/Linux: python3 -m venv venv and source venv/bin/activate.
  • Install dependencies: python -m pip install -r requirements.txt (like npm install).
  • Have Python 3 installed (check with python3 --version or python --version).

You’ll also need a MongoDB account, which we’ll cover below.

Step-by-Step Guide

Below are the steps to complete Sprint 1, with explanations and JavaScript analogies to help you understand the process.

Step 1: Set Up a MongoDB Account and Cluster

Goal: Create a MongoDB database to store monster data.

What to Do:

  1. Sign Up for MongoDB Atlas:

    • Go to MongoDB Atlas and create a free account.
    • Choose the free tier “Shared Cluster” during setup, which is sufficient for this project.
    • This is like setting up a MongoDB Atlas instance for a Node.js app.
  2. Create a Cluster:

    • Follow the prompts to create a cluster (e.g., name it “BandersnatchCluster”).
    • Select a cloud provider (e.g., AWS) and region. The default settings are fine for beginners.
    • This is similar to initializing a database for a JavaScript backend.
  3. Configure Network Access:

    • In MongoDB Atlas, go to “Network Access” and add your IP address to the allow list (use “0.0.0.0/0” for testing to allow all IPs, but be cautious in production).
    • This ensures your Python app can connect to the database, like configuring MongoDB access in a Node.js project.
  4. Create a Database User:

    • Go to “Database Access” and add a new user with a username and password.
    • Note these credentials, as you’ll need them for the connection string.
  5. Get the Connection String:

    • In the “Clusters” section, click “Connect” and select “Connect your application.”
    • Copy the connection string, which looks like:
      mongodb+srv://<username>:<password>@<cluster>.<project_id>.mongodb.net/?retryWrites=true&w=majority
      
    • Replace <username> and <password> with the credentials you created.

JavaScript Analogy:

  • This is like setting up MongoDB Atlas for a Node.js app, where you’d get a connection string to use with Mongoose.
  • The connection string is stored securely, similar to how you’d store it in a .env file in Node.js.

Tips:

  • If you’re new to MongoDB, think of a “cluster” as a server hosting your database and a “database” as a specific collection of data (like a JavaScript object with multiple collections).

Step 2: Configure the Connection String in Your Project

Goal: Store the MongoDB connection string securely in your project.

What to Do:

  1. Create a .env File:

    • In the project root (BandersnatchStarter/), create a file named .env.
    • Add your connection string:
      DB_URL=mongodb+srv://<username>:<password>@<cluster>.<project_id>.mongodb.net/?retryWrites=true&w=majority
      
    • Replace placeholders with your actual credentials and cluster details.
  2. Install python-dotenv:

    • The requirements.txt file likely includes python-dotenv, which loads environment variables, similar to the dotenv package in Node.js.
    • If not, install it: pip install python-dotenv.
  3. Load the Environment Variable in Python:

    • In your Python code (e.g., app/main.py or a new file like app/database.py), load the .env file using:
      from dotenv import load_dotenv
      import os
      load_dotenv()
      db_url = os.getenv("DB_URL")
    • This is like require('dotenv').config() and process.env.DB_URL in Node.js.

JavaScript Analogy:

  • The .env file and python-dotenv work exactly like dotenv in Node.js, keeping sensitive data out of your code.
  • Think of os.getenv() as process.env.

Tips:

  • Add .env to .gitignore to avoid committing sensitive data (the repository likely already does this).
  • Test the connection string by printing db_url to ensure it’s loaded correctly.

Step 3: Connect to MongoDB Using pymongo

Goal: Write Python code to connect to MongoDB and verify the connection.

What to Do:

  1. Install pymongo:

    • The requirements.txt file includes pymongo, the Python library for MongoDB, similar to mongoose in Node.js.
    • Verify it’s installed: pip show pymongo.
  2. Write Connection Code:

    • In a Python file (e.g., app/database.py or app/main.py), create a function to connect to MongoDB:
      from pymongo import MongoClient
      def connect_to_db():
          client = MongoClient(db_url)
          return client
    • MongoClient is like mongoose.connect() in JavaScript, establishing a connection to the database.
    • The db_url is the connection string from your .env file.
  3. Test the Connection:

    • Add code to select a database and collection:
      db = client["bandersnatch"]
      collection = db["monsters"]
    • This creates a database named “bandersnatch” and a collection named “monsters” (like a table in SQL or a collection in Mongoose).
    • Test the connection by printing the list of databases:
      print(client.list_database_names())

JavaScript Analogy:

  • pymongo is like mongoose, but it’s less opinionated and doesn’t require schemas (MongoDB is schema-less by default).
  • A “collection” in MongoDB is like an array of JSON objects, similar to what you’d store with Mongoose.

Tips:

  • If the connection fails, check your MongoDB connection string, IP allow list, and credentials.
  • MongoDB databases and collections are created automatically when you insert data, unlike SQL databases.

Step 4: Create and Insert Monster Data

Goal: Insert sample monster data into the MongoDB collection.

What to Do:

  1. Design Monster Data:

    • Decide on the structure of your monster data. For example:
      monster = {
          "name": "Dragon",
          "strength": 100,
          "type": "Fire",
          "speed": 80
      }
    • This is like a JSON object you’d send in a POST request in a JavaScript app.
  2. Insert Data into MongoDB:

    • Use pymongo to insert a single monster:
      result = collection.insert_one(monster)
      print(result.inserted_id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment