bson.errors.InvalidDocument: 无法编码对象: True
我在用Python往Mongo里插入文档时遇到了一个错误。
document = {u'Status': 'Active',
u'Installation': {u'IsFrugal': True, u'IsFeatureSet': True, u'IsEvolving': True, u'IsAffordable': True},
u'AutoList': [u'IsFeatureSet', u'IsAffordable', u'IsFrugal']
}
错误信息是
C:\Python27\lib\site-packages\pymongo-2.5.1_-py2.7-win32.egg\pymongo\collection.
py:357: RuntimeWarning: couldn't encode - reloading python modules and trying ag
ain. if you see this without getting an InvalidDocument exception please see htt
p://api.mongodb.org/python/current/faq.html#does-pymongo-work-with-mod-wsgi
continue_on_error, self.__uuid_subtype), safe)
Traceback (most recent call last):
File "C:\Python27\lib\runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "C:\Python27\lib\runpy.py", line 72, in _run_code
exec code in run_globals
File "D:\Office_Drive\RetailReco\contactsnew\rrpython\rcauto.py", line 28, in
<module>
rceval.AutoProcess()
File "C:\Python27\lib\site-packages\rrpython-0.1-py2.7.egg\rrpython\automizati
on.py", line 67, in AutoProcess
self._configdb[RCEVALPMTS].save(tempdict)
File "C:\Python27\lib\site-packages\pymongo-2.5.1_-py2.7-win32.egg\pymongo\col
lection.py", line 266, in save
return self.insert(to_save, manipulate, safe, check_keys, **kwargs)
File "C:\Python27\lib\site-packages\pymongo-2.5.1_-py2.7-win32.egg\pymongo\col
lection.py", line 357, in insert
continue_on_error, self.__uuid_subtype), safe)
bson.errors.InvalidDocument: Cannot encode object: True
"bson.errors.InvalidDocument: Cannot encode object: True"
当我使用“true”这个字符串时,它能正常工作,但我想插入的是布尔值,而不是字符串。
我尝试插入简单的 {"name": True}
时,它能正常工作。这是怎么回事?哪里出了问题?
2 个回答
-4
这主要是因为在json中并没有True
这个东西(其实在mongo中用的是bson格式,但它们很相似)。与其手动把这个改成'true'
的字符串,不如直接把你的文档编码成json格式,然后再插入到mongo中:
import json
document = {u'Status': 'Active',
u'Installation': {u'IsFrugal': True, u'IsFeatureSet': True, u'IsEvolving': True,
u'IsAffordable': True},
u'AutoList': [u'IsFeatureSet', u'IsAffordable', u'IsFrugal']
}
jsonified_document = json.dumps(document)
1
根据错误信息来看,tempdict
可能是一个值 True
,而不是一个要插入的数据字典。这可能是因为应用程序的其他地方出现了问题,比如 rrpython 这个库。