Skip to content

MongoDB

FastAPI Users provides the necessary tools to work with MongoDB databases thanks to mongodb/motor package for full async support.

Setup database connection and collection

Let's create a MongoDB connection and instantiate a collection.

import motor.motor_asyncio
from fastapi import FastAPI
from fastapi_users import models
from fastapi_users.db import MongoDBUserDatabase


class User(models.BaseUser):
    pass


class UserCreate(models.BaseUserCreate):
    pass


class UserUpdate(User, models.BaseUserUpdate):
    pass


class UserDB(User, models.BaseUserDB):
    pass


DATABASE_URL = "mongodb://localhost:27017"
client = motor.motor_asyncio.AsyncIOMotorClient(
    DATABASE_URL, uuidRepresentation="standard"
)
db = client["database_name"]
collection = db["users"]


app = FastAPI()


user_db = MongoDBUserDatabase(UserDB, collection)

You can choose any name for the database and the collection.

Warning

You may have noticed the uuidRepresentation parameter. It controls how the UUID values will be encoded in the database. By default, it's set to pythonLegacy but new applications should consider setting this to standard for cross language compatibility. Read more about this.

Create the database adapter

The database adapter of FastAPI Users makes the link between your database configuration and the users logic. Create it like this.

import motor.motor_asyncio
from fastapi import FastAPI
from fastapi_users import models
from fastapi_users.db import MongoDBUserDatabase


class User(models.BaseUser):
    pass


class UserCreate(models.BaseUserCreate):
    pass


class UserUpdate(User, models.BaseUserUpdate):
    pass


class UserDB(User, models.BaseUserDB):
    pass


DATABASE_URL = "mongodb://localhost:27017"
client = motor.motor_asyncio.AsyncIOMotorClient(
    DATABASE_URL, uuidRepresentation="standard"
)
db = client["database_name"]
collection = db["users"]


app = FastAPI()


user_db = MongoDBUserDatabase(UserDB, collection)

Notice that we pass a reference to your UserDB model.

Info

The database adapter will automatically create a unique index on id and email.

Warning

FastAPI Users will use its defined id UUID as unique identifier for the user, rather than the builtin MongoDB _id.

Next steps

We will now configure an authentication method.