c00p3r.web
c00p3r.web

Reputation: 848

MongoDB, MongoEngine: unique list items

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?

Upvotes: 1

Views: 1670

Answers (1)

Ross
Ross

Reputation: 18111

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)

Upvotes: 3

Related Questions