【发布时间】:2022-01-16 14:56:36
【问题描述】:
我正在练习 Node.js,并且正在创建一个网站,人们可以在其中对事物进行投票,然后获得结果。使用 /coffeeorwater POST 路由进行投票,然后重定向到显示结果的 /results1 路由。
问题 = 投票从前端的表单到 Node 到 MongoDB,然后返回到 Node,然后到 /results1 路由,但有时显示的投票数落后于数据库中的数字。
我认为这与 Node 的异步特性有关,或者可能与我设置路由的方式有关,因为必须发送数据然后快速返回。
到目前为止,我尝试的是搜索“使用 Node 返回的数据不立即更新”和“从 MongoDB 返回数据时计数延迟”之类的内容,但我还没有找到解决方案。我完全是自学成才,所以如果有任何明显的或应该很容易找到的,我深表歉意。
const express = require('express');
const application = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
application.set('view engine', 'ejs');
application.use(bodyParser.urlencoded({ extended: true }));
application.use(express.json());
mongoose.connect(process.env.DATABASE_PASSWORD)
.then(console.log('Database connected'));
const db = mongoose.connection;
application.get('/', (request, response) => {
response.render('index', {
data: '1234',
});
});
application.post('/coffeeorwater', async (request, response, next) => {
const choice = request.body.coffeeorwater;
const updatevotes = async () => {
if (choice == 'coffee') {
db.collection('data').update(
{ question: 'coffeeorwater' },
{
$inc: {
coffeevotes: 1
}
}
)
}
if (choice == 'water') {
db.collection('data').update(
{ question: 'coffeeorwater' },
{
$inc: {
watervotes: 1
}
}
)
}
};
await updatevotes();
console.log('POST made');
response.redirect('/results1');
});
application.get('/results1', async (request, response) => {
const results = await db.collection('data').findOne({
question: 'coffeeorwater'
});
response.render('results1', {
coffeevotes: results.coffeevotes,
watervotes: results.watervotes,
});
});
application.listen(8080, () => {
console.log('Listening here');
});
【问题讨论】:
-
POST 方法的响应可以显示更新的结果。因此,
updateOne可以替换为findOneAndUpdate方法,该方法可以返回更新后的文档,该文档可以显示在 POST 响应中。这是一个选项。
标签: javascript node.js database mongodb express