File size: 1,832 Bytes
cb7f5fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import motor.motor_asyncio
import os
from bson.objectid import ObjectId

MONGO_DETAILS = os.getenv("MONGO_DETAILS")

client = motor.motor_asyncio.AsyncIOMotorClient(MONGO_DETAILS)

database = client.fastapi_students

students_collection = database.get_collection("students")


# helpers
def student_helper(student) -> dict:
    return {
        "id": str(student["_id"]),
        "name": student["name"],
        "email": student["email"],
        "password": student["password"],
        "year": student["year"],
        "branch": student["branch"],
        "division": student["division"],
        "pin": student["pin"],
        "gpa": student["gpa"],
        "phone": student["phone"],
        "address": student["address"],
    }

# Retrieve all students present in the database


async def get_all():
    students = []
    async for student in students_collection.find():
        students.append(student_helper(student))
    return students


async def add(student_data: dict) -> dict:
    student = await students_collection.insert_one(student_data)
    new_student = await students_collection.find_one({"_id": student.inserted_id})
    return student_helper(new_student)


async def get(PIN: str) -> dict:
    student = await students_collection.find_one({"pin": PIN})
    if student:
        return student_helper(student)

async def update(PIN: str, updated_data: dict) -> dict:
    if not updated_data:
        return False
    student = await students_collection.find_one({"pin": PIN})
    if student:
        students_collection.update_one({"pin": PIN}, {"$set": updated_data})
        return True
    return False


async def delete(PIN: str):
    student = await students_collection.find_one({"pin": PIN})
    if student:
        await students_collection.delete_one({"pin": PIN})
        return True
    return False