0

I am trying to save an object in mongodb using pymongo. I am calling an api which gives me and object and by iterating through object i am able to get fields and values. But problem is there may be some fields whose value is also an object and when i tried to store such fileds in mongodb i am getting errors.

Error is document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping

models.py

class UnusedResources(Document):
    field1 = fields.StringField(max_length=20)
    field2 = fields.DictField()

python shell

object = API   #calling api
d = dict()

d['field1'] = None
d['field2'] = object.__dict__  #converted all fields of object into dict and stored in d['field2']

client = MongoClient('127.0.0.1', 27017)
db = client.CESdatabase
collection = db.registration_unusedresources
collection.insert_one(d)

fields inside object

{
 'additional_properties': {}, 
 'id': '/subscriptions/XXX/resourceGroups/auth-user-api/providers/Microsoft.Network/loadBalancers/XXX', 
 'name': 'XXX',  
 'sku': <azure.mgmt.network.v2018_11_01.models.load_balancer_sku_py3.LoadBalancerSku object at 0x0000000004E05D30>,
 'probes': [<azure.mgmt.network.v2018_11_01.models.probe_py3.Probe object at 0x0000000004E05DA0>], 
 'inbound_nat_rules': [], 
 'inbound_nat_pools': [], 
 'outbound_rules': None
}
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
Vikas Gautam
  • 239
  • 1
  • 4
  • 21

1 Answers1

1

You have an instance of azure.mgmt.network.v2018_11_01.models.load_balancer_sku_py3.LoadBalancerSku and azure.mgmt.network.v2018_11_01.models.probe_py3.Probe in your API response. This is something that Mongo cannot store (rightly so). You need to determine how you want to serialize those as well.

cwallenpoole
  • 79,954
  • 26
  • 128
  • 166