Home > Mobile >  pymongo | InvalidOperation while trying to return result
pymongo | InvalidOperation while trying to return result

Time:09-29

I've been trying to make something using MongoDB with the help of pymongo python package but I've encountered a error that I can't solve. So basically, I used the collection.find() function to assign the returned data to a variable and then tried to return a row using result["role.id"] as you can see in the code below. Unfortunately, it gives me this error when it tries to return the result:

InvalidOperation: cannot set options after executing query

Code:

def post_exists_and_return_value(collection, id):
result = None
if collection == "muted_role":
    result = muted_role_collection.find({"_id": id})
elif collection == "member_role":
    result = member_role_collection.find({"_id": id})
if len(list(result)) == 1:
    return result["role_id"] # error happens here (debugging mode flagged it)
else:
    return False

CodePudding user response:

The find() method returns a Cursor instance, per the documentation here. So your current code is attempting to access a field of the first document, but it is doing so against the cursor rather than the first result of the cursor.

Your two options are:

  1. Use find_one() method instead, documented just a little bit earlier on the same page here
  2. Iterate your cursor to operate on the first document in the results held by the cursor.

It seems like the first is perfectly reasonable for what you are attempting to do here.

  • Related