 72aa68c462
			
		
	
	72aa68c462
	
	
	
		
			
			* Use a generic Protocol model for User instead of Pydantic
* Remove UserDB Pydantic schema
* Harmonize schema variable naming to avoid confusions
* Revamp OAuth account model management
* Revamp AccessToken DB strategy to adopt generic model approach
* Make ID a generic instead of forcing UUIDs
* Improve generic typing
* Improve Strategy typing
* Tweak base DB typing
* Don't set Pydantic schemas on FastAPIUsers class: pass it directly on router creation
* Add IntegerIdMixin and export related classes
* Start to revamp doc for V10
* Revamp OAuth documentation
* Fix code highlights
* Write the 9.x.x ➡️ 10.x.x migration doc
* Fix pyproject.toml
		
	
		
			
				
	
	
	
		
			2.4 KiB
		
	
	
	
	
	
	
	
			
		
		
	
	Beanie
FastAPI Users provides the necessary tools to work with MongoDB databases using the Beanie ODM.
Setup database connection and collection
The first thing to do is to create a MongoDB connection using mongodb/motor (automatically installed with Beanie).
--8<-- "docs/src/db_beanie.py"
You can choose any name for the database.
Create the User model
As for any Beanie ODM model, we'll create a User model.
--8<-- "docs/src/db_beanie.py"
As you can see, FastAPI Users provides a base class that will include base fields for our User table. You can of course add you own fields there to fit to your needs!
!!! tip "Document ID is a MongoDB ObjectID" Beanie automatically manages document ID by encoding/decoding MongoDB ObjectID.
If you want to use another type, like UUID, you can override the `id` field:
```py
import uuid
from pydantic import Field
class User(BeanieBaseUser[uuid.UUID]):
    id: uuid.UUID = Field(default_factory=uuid.uuid4)
```
Notice that `BeanieBaseUser` expects a generic type to define the actual type of ID you use.
!!! info
The base class is configured to automatically create a unique index on id and email.
Create the database adapter
The database adapter of FastAPI Users makes the link between your database configuration and the users logic. It should be generated by a FastAPI dependency.
--8<-- "docs/src/db_beanie.py"
Notice that we pass a reference to the User model we defined above.
Initialize Beanie
When initializing your FastAPI app, it's important that you initialize Beanie so it can discover your models. We can achieve this using a startup event handler on the FastAPI app:
from beanie import init_beanie
@app.on_event("startup")
async def on_startup():
    await init_beanie(
        database=db,  # (1)!
        document_models=[
            User,  # (2)!
        ],
    )
- 
This is the dbMotor database instance we defined above.
- 
This is the Beanie Usermodel we defined above. Don't forget to also add your very own models!