I return object from the MongoDB database, using python. I want to see now if the property revokedTokens exists. This is my code:
usersCollection = db["users"]
searchQuery = { "username": username }
user = usersCollection.find_one(searchQuery)
print("user is:")
print(user)
if hasattr(user, "revokedTokens"):
print("appending")
user["revokedTokens"].append("another")
#user["revokedTokens"].append(jwt)
else:
print("adding first element")
user["revokedTokens"] = ["first"]
#user["revokedTokens"] = [jwt]
but I always end up in the wrong print ( print("adding first element")
) , so I don't know how to check this. Thanks everyone for correcting me, I am a python newbie!
CodePudding user response:
Generally, it is probably better practice to use the $exists
MongoDB operator.
To make your code work (if you don't want to use the MongoDB query way), you should replace:
if hasattr(user, "revokedTokens"):
with
if "revokedTokens" in user:
This is because the query returns a dict
object, and not a structured class
CodePudding user response:
find_one returns a dict so what you need to ask is if "revokedTokens" in user
or if user.get('revokedTokens') is not None