Skip to content

Commit 4995fbf

Browse files
committed
pymongo and create_student
1 parent 8e0ca16 commit 4995fbf

File tree

1 file changed

+8
-9
lines changed

1 file changed

+8
-9
lines changed

app.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,17 @@
99
from typing_extensions import Annotated
1010

1111
from bson import ObjectId
12-
import asyncio
12+
import pymongo
1313
from pymongo import AsyncMongoClient
1414
from pymongo import ReturnDocument
15+
from pymongo.server_api import ServerApi
1516

1617

1718
app = FastAPI(
1819
title="Student Course API",
1920
summary="A sample application showing how to use FastAPI to add a ReST API to a MongoDB collection.",
2021
)
21-
client = AsyncMongoClient(os.environ["MONGODB_URL"])
22+
client = AsyncMongoClient(os.environ["MONGODB_URL"],server_api=pymongo.server_api.ServerApi(version="1", strict=True,deprecation_errors=True))
2223
db = client.college
2324
student_collection = db.get_collection("students")
2425

@@ -100,13 +101,11 @@ async def create_student(student: StudentModel = Body(...)):
100101
101102
A unique `id` will be created and provided in the response.
102103
"""
103-
new_student = await student_collection.insert_one(
104-
student.model_dump(by_alias=True, exclude=["id"])
105-
)
106-
created_student = await student_collection.find_one(
107-
{"_id": new_student.inserted_id}
108-
)
109-
return created_student
104+
new_student = student.model_dump(by_alias=True, exclude=["id"])
105+
result = await student_collection.insert_one(new_student)
106+
new_student["_id"] = result.inserted_id
107+
108+
return new_student
110109

111110

112111
@app.get(

0 commit comments

Comments
 (0)