File size: 1,491 Bytes
1220b7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""

mongodb.py — MongoDB connection and collection access for FitMate



Uses pymongo (sync) for seed scripts. Motor (async) will wrap this for FastAPI.

"""

import os
from pymongo import MongoClient
from pymongo.collection import Collection
from pymongo.database import Database

try:
    from dotenv import load_dotenv
    load_dotenv()
except ImportError:
    pass

MONGODB_URL = os.getenv("MONGODB_URL", "mongodb://localhost:27017")
MONGODB_DB_NAME = os.getenv("MONGODB_DB_NAME", "fitmate_db")

def get_db() -> Database:
    """Get synchronous MongoDB database instance."""
    client = MongoClient(MONGODB_URL)
    return client[MONGODB_DB_NAME]

def get_collection(collection_name: str) -> Collection:
    """Get a specific collection from the database."""
    db = get_db()
    return db[collection_name]

def create_indexes():
    """Create MongoDB indexes for performance. Run once during setup."""
    db = get_db()

    db["tcm_ingredients"].create_index("mandarin_name")
    db["tcm_ingredients"].create_index("indonesian_name")
    db["tcm_ingredients"].create_index("latin_name")
    db["tcm_ingredients"].create_index([("mandarin_name", "text"), ("indonesian_name", "text")])

    db["safety_rules"].create_index("ingredient_id")
    db["safety_rules"].create_index("condition_logic")

    db["scan_logs"].create_index("scanned_at")
    db["scan_logs"].create_index("warning_triggered")

    print("[ok] MongoDB indexes created")