Python MongoDB、MongoEngine:唯一列表项

Python MongoDB、MongoEngine:唯一列表项,python,mongodb,flask,mongoengine,Python,Mongodb,Flask,Mongoengine,所以我正在用Flask和Mongoengine制作一个简单的比萨饼投票应用程序。 以下是投票类文档: 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 o

所以我正在用Flask和Mongoengine制作一个简单的比萨饼投票应用程序。 以下是投票类文档:

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))
我搞不懂的是,如何使“选民”中的参考文献独一无二。 不是整个字段,而是列表中的项目不能重复,因此一个用户只能为一个比萨饼投票一次

目标是禁止一个用户对比萨饼投两次票


有什么想法吗?

解决这个问题的最好方法是使用MongoDB的原生功能。您可以使用两个运算符:

1) 使用“查询出我已完成的任何投票”,并在查询匹配时插入:

updated = Votes.objects(pizza=Spicy, 
                        vote=FiveStar, 
                        nin__voters=Rozza).update(push__voters=Rozza)
2) 仅当值不在数组中时,才使用它将值添加到数组中。我们还可以在此处添加
upsert
标志,如果对象不存在,我们将插入:

updated = Votes.objects(pizza=Spicy, 
                        vote=FiveStar, 
                        upsert=True).update(addToSet__voters=Rozza)

为什么不使用$addToSet更新字段呢?如果他们投票不止一次,那也没关系,因为他们只会在选民中投票一次。或者,对投票者执行使用$nin的更新查询。@Ross您能解释一下$addToSet和$nin是什么吗?