simple voting system with MongoDB

后端 未结 1 2038
不思量自难忘°
不思量自难忘° 2021-01-01 02:19

quick question I have a list of articals in mongodb and I want users to be able to upvote or down vote the artical.

My first way would be in the artical collection t

相关标签:
1条回答
  • 2021-01-01 02:21

    When you would do it that way, you wouldn't track which user has already voted, so users can vote multiple times. That's surely not in your interest.

    For that reason I would add an array "votes" to each article which includes an object for each vote which uniquely identifies the user who made it:

    votes: [ 
            { voter:"name or ID or IP address or some other unique identifier for the person who voted",
              vote:-1 },
            { voter:"someone else",
              vote:1 },
            { voter:"and someone entirely different",
              vote:-1 }
        ]
    

    When you create an unique index over the article ID and votes.voter, you have already ensured that nobody can vote twice for an article.

    When you use a value of "-1" for downvote and "1" for upvote you can calculate the total score of an article by using the $sum aggregate function (It would also easily allow you to introduce weighted votes later, when you feel like it).

    0 讨论(0)
提交回复
热议问题