I figured it out!
Here's what I changed.
First of all, in the jinja2 template, I checked the email like this: {% if current_user.get_id() in artwork.votes %}
instead of {% if artwork['votes'][current_user.get_id()] is defined%}
.
Next, I changed the upvote function to be like this:
@app.route("/upvote", methods=["POST"])
def upvote():
if current_user.is_authenticated:
artwork = DisplayArtwork.objects(filename=request.form["filename"]).first()
if artwork:
user_email = current_user.get_id()
if user_email in artwork.votes:
artwork.update(pull__votes=user_email)
return "downvoted", 200
else:
artwork.update(add_to_set__votes=user_email)
return "upvoted", 200
return "Failed to upvote", 500
return "Login to upvote", 401
artwork.update(pull__votes=user_email)
won't throw KeyError so I changed it to manually check whether the email was in the list and then decide what to do.
I also forgot to add .first()
to get one artwork instead of a list.