使用node.js,mongodb和ejs实现投票系统

时间:2018-09-25 22:49:34

标签: node.js mongodb ejs

我对node.JS和ejs很陌生。我已经使用上述技术搜索了how to implement real-time voting system like Stackoverflow voting。但是我不知道该怎么做。

这是我的前端代码:

<% for (var i = 0; i < gamePasses.length; i++) {%>
    <form dir="ltr">
        <tr>
            <td>
                <%= i + 1 %>
            </td>
            <td>
                <%= gamePasses[i].teamName %>
            </td>
            <td>
                <%= gamePasses[i].password %>
            </td>
            <td>
                <%= gamePasses[i].votes %>
            </td>
            <td onclick="vote('<%= gamePasses[i].password %>')">
                <i class="material-icons">
                    thumb_up
                </i>
            </td>
        </tr>

    </form>
<% } %>

<script>
    function vote(pass) {
        $.post('/user/vote/' + pass)
    }
    function passSubmit() {
        $.post('/user/gamePassword', {
            gamePassword: $('#password').val()
        }).done(() => {
            window.location.assign('/user/scoreboard')
        })
    }
</script>

后端代码:

uter.post('/vote/:gamePassword', (req, res) => {
    gamePassword = req.params.gamePassword;
    gamePassModel.find({password: gamePassword}, (err, result) => {
        if (err) console.log(err)
        else {
            result.votes += 1
            result.save((err) => {
                if (err) console.log(err)
            })
        }
    })
})

此代码问题是:

  1. 不支持实时投票

  2. 每个用户可以多次投票

如果有人能帮助我,我将很感激

1 个答案:

答案 0 :(得分:1)

要禁止同一用户进行多次投票,您可以这样想。没有测试它,但是逻辑应该起作用。

uter.post('/vote/:gamePassword', (req, res) => {
gamePassword = req.params.gamePassword;

//you can retrieve the voter id the way you want (in this case I assumed the query string contains it)
let voterId = req.query.voterId

gamePassModel.find({password: gamePassword}, (err, result) => {
    if (err) console.log(err)
    else {

        //votes in not a number anymore. Now it's an array of IDs, you have to change the model (in Mongoose, I suppose)

        if(~result.votes.indexOf(voterId)) {
           result.votes.push(voterId)  

            //I'm pretty sure you cannot call save() like you do on this object, but this is not part of the question here, check the mongoose docs
            result.save((err) => {
            if (err) res.json({error:err});
           })          
        } else res.json({ error: "you already voted" });


    }
})
})

现在,当您想获得某物的总票数时,您必须进行计数查询(仍然假设mongodb / mongoose https://mongoosejs.com/docs/api.html#model_Model.count