my documents look like this : { "_id" : 5, "hunger" : 5, "energy" : 50 }
I'm calling this function..
def getEnergy(_id) -> int:
record = db.systems.find({"_id":_id}) # systems is the collection
return record[0]['energy']
and getting this error..
(...)
File "C:\Users\mateo\AppData\Roaming\Python\Python39\site-packages\pymongo\cursor.py", line 692, in __getitem__
for doc in clone:
File "C:\Users\mateo\AppData\Roaming\Python\Python39\site-packages\pymongo\cursor.py", line 1238, in next
if len(self.__data) or self._refresh():
File "C:\Users\mateo\AppData\Roaming\Python\Python39\site-packages\pymongo\cursor.py", line 1155, in _refresh
self.__send_message(q)
File "C:\Users\mateo\AppData\Roaming\Python\Python39\site-packages\pymongo\cursor.py", line 1044, in __send_message
response = client._run_operation(
File "C:\Users\mateo\AppData\Roaming\Python\Python39\site-packages\pymongo\mongo_client.py", line 1424, in _run_operation
return self._retryable_read(
File "C:\Users\mateo\AppData\Roaming\Python\Python39\site-packages\pymongo\mongo_client.py", line 1525, in _retryable_read
return func(session, server, sock_info, secondary_ok)
File "C:\Users\mateo\AppData\Roaming\Python\Python39\site-packages\pymongo\mongo_client.py", line 1420, in _cmd
return server.run_operation(
File "C:\Users\mateo\AppData\Roaming\Python\Python39\site-packages\pymongo\server.py", line 98, in run_operation
message = operation.get_message(
File "C:\Users\mateo\AppData\Roaming\Python\Python39\site-packages\pymongo\message.py", line 351, in get_message
request_id, msg, size, _ = _op_msg(
File "C:\Users\mateo\AppData\Roaming\Python\Python39\site-packages\pymongo\message.py", line 743, in _op_msg
return _op_msg_uncompressed(
bson.errors.InvalidDocument: cannot encode object: <pymongo.cursor.Cursor object at 0x0000021E52535670>, of type: <class 'pymongo.cursor.Cursor'>
Sometimes the function works just fine, and sometimes it throws an error. It seems to be a problem with the server but I can't figure out what exactly the problem is.
CodePudding user response:
If the error is in that function (which we can't 100% tell as you've only posted half the stack trace), you will get this error is you are passing a cursor into the function; this snippet reproduces the error:
from pymongo import MongoClient
db = MongoClient()['mydatabase']
def getEnergy(_id) -> int:
record = db.systems.find({"_id":_id}) # systems is the collection
return record[0]['energy']
foo = db.somecollection.find()
getEnergy(foo)
error:
bson.errors.InvalidDocument: cannot encode object: <pymongo.cursor.Cursor object at 0x0000019DB0A0B070>, of type: <class 'pymongo.cursor.Cursor'>
You need to examine where you are calling getExport()
and check the parameter you are passing in isn't a cursor object.