簡體   English   中英

使用 node.js、mongodb 和 ejs 實現投票系統

[英]implement voting system using node.js, mongodb and ejs

我對 node.JS 和 ejs 很陌生。 我已經搜索了how to implement real-time voting system like Stackoverflow voting使用上述技術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. 每個用戶可以多次投票

如果有人可以幫助我,我將不勝感激

對於禁止同一個用戶進行多次投票,你可以這樣想。 沒有測試它,但邏輯應該有效。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM