0

I have a several comples mongo models. For example, a User that references a Role with some properties. Now when I retrieve users, I want the role property to be populated with those of the referenced role object, not the object id.


from mongoengine import *

connect('test_database')

class Role(Document):
    name = StringField(required=True)
    description = StringField(required=True)

class User(Document):
    role = ReferenceField(Role, reverse_delete_rule=DENY)

r = Role(name='test', description='foo').save()
User(role=r).save()

print(User.objects().select_related()[0].to_mongo().to_dict())

# prints: {'_id': ObjectId('5c769af4e98fc24f4a82fd99'), 'role': ObjectId('5c769af4e98fc24f4a82fd98')}
# want:   {'_id': '5c769af4e98fc24f4a82fd99', 'role': {'name' : 'test', 'description' : 'foo'}}

How do I go about achieving this, for any complex mongoengine object?

ahammond
  • 31
  • 6

1 Answers1

0

Mongoengine does not provide anything out of the box but you can either define a method (e.g to_dict(self)) on your Document class, or use a serialisation library like marshmallow-mongoengine

bagerard
  • 5,681
  • 3
  • 24
  • 48