MongoDB的简单投票系统 [英] simple voting system with MongoDB

查看:86
本文介绍了MongoDB的简单投票系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速问题,我在mongodb中有一篇文章列表,希望用户能够对文章进行投票或否决.

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

我的第一种方法是在艺术收藏中有两行称为upvote和downvote,它们的编号为 赞:360 downvote:102;

My first way would be in the artical collection to have two rows called upvote and downvote they would have numbers like upvote:360 downvote:102;

然后我需要通过求和来排序 upvote-downvote,这将显示艺术品的总体喜欢程度.

then I would need to order this by doing a sum upvote-downvote this would show the total likes of the artical.

我的问题是在mongoDB中,这是做到这一点的最佳方法,还是我最好先进行一次投票",然后再以那一票进行订购.

My question is in the mongoDB is this the best way to do it or am I better off with one "vote" and then just order it by that vote.

谢谢

推荐答案

以这种方式进行操作时,您将不会跟踪哪个用户已经投票,因此用户可以多次投票.当然,这不符合您的利益.

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 }
    ]

当您在文章ID和votes.voter上创建唯一索引时,您已经确保没有人可以对文章进行两次投票.

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.

当您将"-1"的值用于否决票,将"1"的值用于否决票时,您可以使用$ sum聚合函数来计算文章的总分(这也很容易让您稍后引入加权投票,当你觉得喜欢的时候.)

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).

这篇关于MongoDB的简单投票系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆