From 834a42473d7bf793e1efe11d9db9030b162aa3d4 Mon Sep 17 00:00:00 2001 From: JonathanCheng0101 <77355451+JonathanCheng0101@users.noreply.github.com> Date: Mon, 10 Mar 2025 17:19:09 -0600 Subject: [PATCH] Create dataFromMongoDB A Fast API program that the frontend side can call and get all the data from MongoDB --- dataFromMongoDB | 52 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 dataFromMongoDB diff --git a/dataFromMongoDB b/dataFromMongoDB new file mode 100644 index 0000000..6f27ddc --- /dev/null +++ b/dataFromMongoDB @@ -0,0 +1,52 @@ +# main.py +from fastapi import FastAPI, HTTPException +import motor.motor_asyncio +import uvicorn + +app = FastAPI() + +# Connect to MongoDB (adjust the connection string as needed) +client = motor.motor_asyncio.AsyncIOMotorClient("mongodb://localhost:27017") +db = client.news # use your database name + +@app.get("/geojson") +async def get_geojson(): + try: + # Retrieve all documents from the articles collection + cursor = db.articles.find({}) + articles = await cursor.to_list(length=1000) + + # Convert each document to a GeoJSON Feature + features = [] + for article in articles: + geo = article.get("geoJson") + if not geo: + continue # Skip if no geoJson field is present + + feature = { + "type": "Feature", + "geometry": geo.get("geometry"), + "properties": { + "title": article.get("title"), + "description": article.get("description"), + "url": article.get("url"), + "publishedAt": article.get("publishedAt"), + #"city": article.get("city"), + #"name": geo.get("properties", {}).get("name") + } + } + features.append(feature) + + # Assemble the FeatureCollection + feature_collection = { + "type": "FeatureCollection", + "features": features + } + + return feature_collection + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + +if __name__ == "__main__": + # Run the server on port 3040 (or change as needed) + uvicorn.run("main:app", host="0.0.0.0", port=3040, reload=True)