简体   繁体   中英

Why find() method doesn't show the recent data from mongoDb database in Express.Js

When the app.post('/form-submit', funtion(req, res)) method is called then i am expecting it to first save the data using save() , which it did fine but then i call find() method which shows all the data from mongoDB database except the current data that is recently added by save() method.

I want that find() method show the current data as well . But show() method only shows previous data not recent one. And i thing maybe it is Asynchronous problem

//For Put request in index.js
app.post('/form-submit', function(req, res) {

    //To add the current data into database

    connect.then((db) => {
        var newTask = taskSchema({
            Task: req.body.Task
        });
        newTask.save();

    });


    //To show the data into page 'showTask.ejs
    taskSchema.find({}, function(err, val) {
        console.log(res.length);
        res.render('showTask.ejs', { todoTask: val });
    });

});

save is async

it can either return a promise or take a callback (err) => {}

so you fetch information at the time it didn't manage to save yet

app.post('/form-submit', function(req, res) {

    //To add the current data into database

    connect.then((db) => {
        var newTask = taskSchema({
            Task: req.body.Task
        });
        return newTask.save();
    }).then(() => {
        //To show the data into page 'showTask.ejs
        taskSchema.find({}, function(err, val) {
            console.log(res.length);
            res.render('showTask.ejs', { todoTask: val });
        });
    });

});

or:

app.post('/form-submit', async function(req, res) {

    //To add the current data into database

    const db = await connect;
    var newTask = taskSchema({
        Task: req.body.Task
    });
    await newTask.save();

    //To show the data into page 'showTask.ejs
    taskSchema.find({}, function(err, val) {
        console.log(res.length);
        res.render('showTask.ejs', { todoTask: val });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM