【问题标题】:Node.js and MongoDB getting data back from previous update instead of current updateNode.js 和 MongoDB 从以前的更新而不是当前的更新中获取数据
【发布时间】: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


【解决方案1】:

你可以使用Model.findOneAndUpdate

示例代码:

Model.findOneAndUpdate({[where conditions]}, {[data to update]}, {[options]}, callback function());

模型可以是任何猫鼬模型。

选项 =>

-> 新:布尔值(真/假),默认值:假;如果设置为 true,则返回更新后的文档

【讨论】:

  • 请更新您的问题并使代码更具可读性。
【解决方案2】:

对于 db.collection('data').update 首先,它不是异步方法,因此您可以使用回调获取结果或使用猫鼬mongoose Model.updateOne

检查此参考nodejs_mongodb_update

注意:- 如果您仍有问题,请在评论中提及,我会给您举个例子

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 2022-11-02
    相关资源
    最近更新 更多