Overview
The Blackjack API uses MongoDB as a reactive NoSQL database to store game state. MongoDB is ideal for storing the dynamic game documents that include player cards, dealer cards, deck state, and game status.Dependencies
The project uses Spring Data MongoDB Reactive, configured inpom.xml:
Connection Configuration
Local Development
For local development, configure MongoDB connection inapplication-local.yml:
Docker Environment
For Docker deployments, use service names inapplication-docker.yml:
Production Environment
For production, use environment variables inapplication-prod.yml:
Configuration Properties
| Property | Description | Example |
|---|---|---|
spring.data.mongodb.uri | MongoDB connection string | mongodb://localhost:27017/blackjack |
Connection String Format
Document Model
Games are stored as MongoDB documents with the following structure:Document Fields
- id: Unique game identifier (MongoDB ObjectId)
- playerId: Reference to the player (external UUID)
- playerCards: Cards held by the player
- dealerCards: Cards held by the dealer
- deckCards: Remaining cards in the deck
- status: Game status (IN_PROGRESS, PLAYER_WIN, DEALER_WIN, TIE)
Reactive MongoDB Repository
The application uses Spring Data’sReactiveMongoRepository for reactive database operations:
Repository Adapter
The adapter pattern connects the MongoDB repository to the domain layer:Reactive Operations
All MongoDB operations return reactive types:Mono<Game>- Single game or emptyMono<Void>- Completion signal for delete operationsFlux<Game>- Stream of multiple games (if needed)
Example Operations
Save a game:MongoDB Setup
Local Development with Docker
Verify Connection
Connect using MongoDB shell:Best Practices
- Use Connection Pooling: Spring Data MongoDB handles connection pooling automatically
- Reactive Streams: Always use
MonoandFluxfor non-blocking operations - Document Design: Keep game documents denormalized for fast reads
- Indexing: Add indexes on frequently queried fields like
playerId - Error Handling: Use reactive error handling with
onErrorResumeandswitchIfEmpty
Troubleshooting
Connection Issues
If MongoDB connection fails:- Verify MongoDB is running:
docker ps | grep mongo - Check connection string format
- Ensure network connectivity between application and MongoDB
- Review application logs for connection errors