如何在投票应用程序中正确管理选票?
How to properly manage votes in a voting app?
我正在使用 MERN 堆栈制作投票应用程序。我将 mongoose 和 express 用于数据库和后端。
这是我的猫鼬模式:
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",则只会添加一票。
虽然我没有发现该代码有问题,但如果它不起作用,请尝试使用 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等技术解决。
希望对您有所帮助!让我知道它是否有效。
我正在使用 MERN 堆栈制作投票应用程序。我将 mongoose 和 express 用于数据库和后端。
这是我的猫鼬模式:
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",则只会添加一票。
虽然我没有发现该代码有问题,但如果它不起作用,请尝试使用 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等技术解决。
希望对您有所帮助!让我知道它是否有效。