I’m currently working with Beanie ODM, FastAPI and MongoDB and facing a challenge with optimizing the way references are printed in my JSON responses.
Current Situation: For a Booking object, my current output looks like this:
{
"_id": "66691ce3f75184ad17b7abd9",
"account": {
"id": "6630082da4ecb6802b241748",
"collection": "accounts"
},
"hotel": {
"id": "6660c3bb318e44905a3cff19",
"collection": "hotels"
},
"arrival_date": "2024-06-12T00:00:00",
"departure_date": "2024-06-13T00:00:00",
"language": "en",
"observations": "",
"approved": false,
"created_at": "2024-06-12T03:58:27.887000",
"updated_at": "2024-06-12T03:58:27.887000"
}
Desired Output: I want to format the output so that it includes the collection prefix directly in the reference fields, like this:
{
"id": "booking_66691ce3f75184ad17b7abd9",
"account": "account_6630082da4ecb6802b241748",
"hotel": "hotel_6660c3bb318e44905a3cff19",
"arrival_date": "2024-06-12T00:00:00",
"departure_date": "2024-06-13T00:00:00",
"language": "en",
"observations": "",
"approved": false,
"created_at": "2024-06-12T03:58:27.887000",
"updated_at": "2024-06-12T03:58:27.887000"
}
Currently, to achieve this, I am fetching the booking details and then formatting each booking object individually. This approach is not optimal, especially when dealing with a large number of bookings (e.g., 10,000 bookings). It requires fetching all bookings and then iterating through each one to apply the formatting function, which is resource-intensive.
I’m considering exploring custom fields in Beanie or creating a new field class that inherits from the existing Field type (Link) to handle this more efficiently.