1

So I'm making a simple pizza-voting app with Flask and Mongoengine. Here's the class for votes document:

class Votes(db.Document):
    # reference to a date the vote started
    vote = db.ReferenceField(VoteArchive)

    # reference to one kind of pizza
    pizza = db.ReferenceField(Pizza)

    # list of references to users that voted for that pizza
    voters = db.ListField(db.ReferenceField(User))

What I'm unable to figure out is how to make references in 'voters' to be unique. NOT the whole field but items in that list not to repeat, so one user could vote for one pizza only once.

The goal is to forbid one user to vote for a pizza twice.

Any ideas?

2
  • Why not update the field using $addToSet then it doesn't matter if they voted more than once, as they will be in voters only once. Alternatively, do an update query that uses $nin for voters. Commented Jul 29, 2013 at 12:42
  • @Ross can U explain what are $addToSet and $nin ? Commented Jul 29, 2013 at 13:00

1 Answer 1

3

The best way to deal with this is to use MongoDB's native features. There are two operators that you could use:

1) Using $nin query out any votes that I have already done and insert if the query matches:

updated = Votes.objects(pizza=Spicy, 
                        vote=FiveStar, 
                        nin__voters=Rozza).update(push__voters=Rozza)

2) Using $addToSet which adds a value to an array only if the value is not in the array already. We can also add the upsert flag here and we will insert if the object doesn't exist:

updated = Votes.objects(pizza=Spicy, 
                        vote=FiveStar, 
                        upsert=True).update(addToSet__voters=Rozza)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.