https://github.com/mongo-express/mongo-express
https://beanie-odm.dev/
https://motor.readthedocs.io/en/stable/tutorial-asyncio.html
https://blog.yevgnenll.me/posts/mongodb-and-express
services:
mongodb:
image: mongo
container_name: mongodb
restart: always
ports:
- ${MONGO_DB_PORT}:${MONGO_DB_PORT}
volumes:
- ~/mongodb:/data/db
environment:
- MONGO_INITDB_ROOT_USERNAME=${MONGO_DB_USERNAME}
- MONGO_INITDB_ROOT_PASSWORD=${MONGO_DB_PASSWORD}
- MONGO_INITDB_DATABASE=${MONGO_DB_DATABASE}
mongo-express:
image: mongo-express
restart: always
ports:
- ${MONGO_EXPRESS_PORT}:${MONGO_EXPRESS_PORT}
environment:
ME_CONFIG_BASICAUTH_ENABLED: true
ME_CONFIG_BASICAUTH_USERNAME: ${MONGO_EXPRESS_USERNAME}
ME_CONFIG_BASICAUTH_PASSWORD: ${MONGO_EXPRESS_PASSWORD}
ME_CONFIG_MONGODB_URL: ${MONGO_EXPRESS_MONGODB_URL}
ME_CONFIG_BASICAUTH_ENABLED: true로 설정해야 Basic Authentication 사용 가능admin, pass# MONGO DB
MONGO_DB_PORT=27017
MONGO_DB_USERNAME=root
MONGO_DB_PASSWORD=1234
MONGO_DB_DATABASE=DB이름
# MONGO EXPRESS
MONGO_EXPRESS_PORT=8081
MONGO_EXPRESS_USERNAME=admin
MONGO_EXPRESS_PASSWORD=1234
MONGO_EXPRESS_MONGODB_URL=mongodb://root:1234@mongodb:27017
localhost:8081로 접속 시 admin, 1234로 로그인 가능asyncio를 사용하여 비동기 방식으로 MongoDB와 상호작용할 수 있어서 FastAPI 프로젝트에 사용하기 적합beanie는 비동기적으로 MongoDB와 상호작용할 수 있는 ODM이므로, 비동기 드라이버인 motor와 함께 사용해야 함$ pip install beanie
motor도 함께 설치됨from typing import Optional
import motor.motor_asyncio
from motor.motor_asyncio import AsyncIOMotorClient
from pydantic import BaseModel
from beanie import Document, Indexed, init_beanie
class Category(BaseModel):
name: str
description: str
# DB에 저장될 모델의 schema
class Product(Document):
name: str # You can use normal types just like in pydantic
description: Optional[str] = None
price: Indexed(float) # You can also specify that a field should correspond to an index
category: Category # You can include pydantic models as well
# Call this from within your event loop to get beanie setup.
async def init():
# Create Motor client
client = AsyncIOMotorClient("mongodb://user:pass@localhost:27017")
# Init beanie with the Product document class
await init_beanie(database=client.db_name, document_models=[Product])
init 메소드의 실행 시점?init 시에 document_models로 Document 모델을 특정하는 이유?Pydantic을 통해 유효성을 검사하여 데이터의 안정성을 높일 수 있음