0

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

Yarneo
  • 2,922
  • 22
  • 30

1 Answers1

1

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.

Steve Rossiter
  • 2,624
  • 21
  • 29
  • I indeed tried your approach, but now unfortunately I am receiving the error: TypeError: ObjectId('556f474ff6e6af0009161525') is not JSON serializable As there are other ObjectIds in my Vouch object – Yarneo Jun 10 '15 at 15:26
  • Ok got it! instead of json.dumps we can do bson.json_util.dumps and it solves that issue. Thanks! – Yarneo Jun 10 '15 at 15:39
  • Ah yes, of course. Easy to forget that mongodb is actually bson – Steve Rossiter Jun 10 '15 at 15:40