Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

194
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda