anvil.server.SerializationError with MongoDB

I have a server side function like this

def get_job_cards(js_id):
      job_cards_col = db['jobcards']
      listing = list(job_cards_col.find({"js_id":js_id}).sort("created_at",-1))
      return listing

It basically returns a sorted list of dicts from my mongoDB collection. But when I pass this list to repeating-panel like this on client side
self.repeating_panel_1.items = anvil.server.call('get_job_cards',self.text_box_js_id.text)

I get following error
anvil.server.SerializationError: Cannot serialize return value from function. Cannot serialize <class 'bson.objectid.ObjectId'> object at msg['response'][0]['_id']

My function works perfectly fine in my own python terminal. I think i suppose to give searchIterator to repeating panel and I am giving it a list of dicts. But I am not sure, Can you please tell me how can I fix this.

Consider

in this light: Valid arguments and return values . This strongly suggests that at least one of your dictionary entries (or nested entries) is a value of a different type.

In fact, the error message tells you the type: bson.objectid.ObjectId. You’ll need to convert this kind of value into something that a server function can return.

1 Like

Thanks. Mongodb returns its “_id” something like this ObjectId(xxxxxxxxx). This thing cause the serialization error. In order to fix this, I just made sure Mongodb don’t send me the “_id” field.
listing = list(job_cards_col.find({"js_id":js_id},{"_id":0}).sort("created_at",-1))

“_id”:0 will fix the error.

A very clean solution is:

from pymongo import MongoClient
from pymongo.cursor import Cursor
import json
from bson import ObjectId

class JSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, ObjectId):
            return str(o)
        if isinstance(o, Cursor):
            return list(o)
        return json.JSONEncoder.default(self, o)

cursor = db["my_collection"].find({})
print(JSONEncoder().encode(cursor))
1 Like