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.
The first ticket focuses on:
- Setting up a MongoDB database: Create a MongoDB cluster and configure access.
- Connecting to MongoDB from Python: Use the
pymongo
library to establish a connection in your Flask app. - Creating monster data: Insert sample monster data (e.g., name, strength, type) into the database.
- 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.
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
andvenv\Scripts\activate
. - macOS/Linux:
python3 -m venv venv
andsource venv/bin/activate
.
- Windows:
- Install dependencies:
python -m pip install -r requirements.txt
(likenpm install
). - Have Python 3 installed (check with
python3 --version
orpython --version
).
You’ll also need a MongoDB account, which we’ll cover below.
Below are the steps to complete Sprint 1, with explanations and JavaScript analogies to help you understand the process.
Goal: Create a MongoDB database to store monster data.
What to Do:
-
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.
-
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.
-
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.
-
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.
-
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).
Goal: Store the MongoDB connection string securely in your project.
What to Do:
-
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.
- In the project root (
-
Install
python-dotenv
:- The
requirements.txt
file likely includespython-dotenv
, which loads environment variables, similar to thedotenv
package in Node.js. - If not, install it:
pip install python-dotenv
.
- The
-
Load the Environment Variable in Python:
- In your Python code (e.g.,
app/main.py
or a new file likeapp/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()
andprocess.env.DB_URL
in Node.js.
- In your Python code (e.g.,
JavaScript Analogy:
- The
.env
file andpython-dotenv
work exactly likedotenv
in Node.js, keeping sensitive data out of your code. - Think of
os.getenv()
asprocess.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.
Goal: Write Python code to connect to MongoDB and verify the connection.
What to Do:
-
Install
pymongo
:- The
requirements.txt
file includespymongo
, the Python library for MongoDB, similar tomongoose
in Node.js. - Verify it’s installed:
pip show pymongo
.
- The
-
Write Connection Code:
- In a Python file (e.g.,
app/database.py
orapp/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 likemongoose.connect()
in JavaScript, establishing a connection to the database.- The
db_url
is the connection string from your.env
file.
- In a Python file (e.g.,
-
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())
- Add code to select a database and collection:
JavaScript Analogy:
pymongo
is likemongoose
, 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.
Goal: Insert sample monster data into the MongoDB collection.
What to Do:
-
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.
- Decide on the structure of your monster data. For example:
-
Insert Data into MongoDB:
- Use
pymongo
to insert a single monster:result = collection.insert_one(monster) print(result.inserted_id
- Use