Home > database >  Node.js and MongoDB getting data back from previous update instead of current update
Node.js and MongoDB getting data back from previous update instead of current update

Time:12-13

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');
});

CodePudding user response:

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

CodePudding user response:

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

  • Related