Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!