Dereference a ReferenceField in Mongoengine

3.3k views Asked by At

I am trying to dereference a reference field on my Flask backend and return the complete object with that certain field dereferenced.

The field I am trying to dereference is defined like this:

vouches_received = db.ListField(db.ReferenceField('Vouch'))

The way I am trying to dereference it is like this:

unverified_vouches = []
for vouch in usr.vouches_received:
    unverified_vouches.append(vouch.to_mongo())

usr.vouches_received = unverified_vouches

However, when I then do:

usr.to_json()

On the object, then I get a ValidationError like so:

ValidationError: u'{...}' is not a valid ObjectId, it must be a
12-byte input of type 'str' or a 24-character hex string

The 3 dots (...) is basically the document dereferenced, it has mostly Strings, a Date Field, and some other reference fields I do not wish to dereference.

I am aware this is a valid error, as it is expecting an ObjectID for the reference field, but then arises the question, how do I succeed at dereferencing that field and return the document.

Thanks

1

There are 1 answers

3
Steve Rossiter On BEST ANSWER

The ListField is expecting elements of ObjectId and because you've de-referenced them it throws that error. I'm not sure this is the most elegant way but could you convert the usr.to_json() to a dict and then replace the vouches_received list with a deferenced list afterwards - I can't test it but something like?

user_dict = json.loads(usr.to_json())

unverified_vouches = []
for vouch in usr.vouches_received:
    user_dict['vouches_received'].append(vouch.to_mongo())

usr_json = json.dumps(user_dict)

A better solution may be to use an EmbededDocument.