我正在練習 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');
});
uj5u.com熱心網友回復:
對于db.collection('data').update 首先它不是異步方法,因此您可以使用回呼獲取結果或使用mongoose mongoose Model.updateOne
檢查此參考nodejs_mongodb_update
注意:-如果您仍然有問題,請在評論中提及我會給您一個例子
uj5u.com熱心網友回復:
你可以使用Model.findOneAndUpdate
示例代碼:
Model.findOneAndUpdate({[where conditions]}, {[data to update]}, {[options]}, callback function());
模型可以是任何貓鼬模型。
選項 =>
-> 新:布林值(真/假),默認值:假;如果設定為 true,則回傳更新的檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/380405.html
標籤:javascript 节点.js 数据库 MongoDB 表达
