You should only call init_beanie
once, and the other connections use from the same connection pool.
I also had some issue and had to figure this out on my own. Cheers!
from fastapi import FastAPI
from beanie import init_beanie
from motor.motor_asyncio import AsyncIOMotorClient
config = dotenv_values(".env")
conn_str = config['MONGO_URI'] # change this to the MONGO-DB connection string
database_name = config['DB_NAME'] # change this to the MONGO-DB database name
@asynccontextmanager
async def lifespan(app: FastAPI):
app.db = AsyncIOMotorClient(conn_str).get_database(database_name)
# ensure to add all the Models created to the `documents_models` list below
await init_beanie(app.db, document_models=[
Customer, CustomerID, CustomerUpdate,
Car, CarID, CarUpdate,
Order,
]) # add the Models to the DB
# models are the database repr you created using beanie. They must all be added inside the documents-models array.
print("DB connection successful...")
yield
print("!! Shutdown complete !!")