Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

198
Visualizações
Node.js and MongoDB getting data back from previous update instead of current update

I'm practicing Node.js and am making a website where people can vote on things and then get the results. The votes are made using the /coffeeorwater POST route which then redirects to the /results1 route which shows the results.

The problem = the votes go from the form on the frontend to Node to MongoDB and back to Node and then to the /results1 route, but sometimes the numbers of votes displayed are behind the numbers that are in the database.

I think it has something to do with the asynchronous nature of Node or maybe the way I've set up the routes since the data has to be sent and then come back quickly.

What I've tried so far is to search for things like "data returning using Node not updating immediately" and "count delayed when returning data from MongoDB" but I haven't found the solution. I'm totally self-taught so my apologies if any of this is obvious or should have been found easily.

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');
});
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

for db.collection('data').update first of all it is not an async method so you can use callback get result OR use mongoose mongoose Model.updateOne

check this reference nodejs_mongodb_update

NOTE:- if you still have an issue then mention on comment I will give you an example

about 4 years ago · Juan Pablo Isaza Relatório

0

You could use Model.findOneAndUpdate

Example Code :

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

Model could be any mongoose model.

options =>

-> new: boolean (true/false), default: false; if set to true, returns the updated document

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda