【问题标题】:How to properly manage votes in a voting app?如何正确管理投票应用程序中的投票?
【发布时间】:2019-03-23 11:29:26
【问题描述】:

我正在使用 MERN 堆栈制作一个投票应用程序。我使用 mongoose 和 express 作为数据库和后端。

这是我的 Mongoose 架构:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

    //create a schema
    const CarrozaSchema = Schema({
      nombre: {
        type: String
      },
      curso: {
        type: String
      },
      votos: Number
    });

    module.exports = Carroza = mongoose.model("carroza", CarrozaSchema);

这是管理选票的路线:

const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");

//Carroza model
const Carroza = require("../../models/Carroza");

// @route   POST api/votos
// @desc    Realizar el voto
// @access  public
router.post("/", (req, res) => {
  Carroza.findOne({ nombre: req.body.nombre })
    .then(carroza => {
      if (!carroza) {
        return res.status(404).json(req.body);
      }

      carroza.votos = carroza.votos + 1; //Here is where the votes are update
      carroza.save();
      res.status(200).json(req.body);
    })
    .catch(err => res.status(404).json(err));
});

module.exports = router;

在前端,用户有一个“carrozas”列表,其中包含一个按钮,可以为他们选择的人添加投票。 this is what the user sees 问题是,如果两个用户同时为同一个“carroza”投票,则只会添加一票。

【问题讨论】:

  • 我没有看到这个问题。你想完成什么?
  • 如果两个人同时(在两个不同的设备中)为同一个 carroza 投票,则只计一票,另一票将丢失。我想解决这个问题

标签: node.js reactjs express mongoose mern


【解决方案1】:

虽然我没有看到该代码有问题,但如果这不起作用,请尝试使用 mongoose findOneAndUpdate()$inc。这是一个例子:

Carroza.findOneAndUpdate({ nombre: req.body.nombre }, {$inc:{votos:1}}, function(err, result){
    if(err) res.json(err);  // whatever error
    else res.json(result);  // whatever result
})

这也将减少查询时间,因为代码很短并且运行单个查询而不是两个。

这类问题一般在大流量的情况下会遇到,通过Redis、RabbitMQ、Kafka等技术解决。

希望对您有所帮助!让我知道它是否有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 2010-10-06
    • 2019-04-03
    • 1970-01-01
    • 2012-03-15
    相关资源
    最近更新 更多