Search code examples
node.jsmongoosenode-async

Nodejs Angularjs Mongoose Query inside Async.series


I am tried to add values to my database and then retrieve the database using mongoose find. The values are added but the mongoose find does not return the values. Below are my codes.

app.post('/api/infosave', function(req,res){
async.series([function (cb){
    dbinfo.remove({}, function(err,result){
        if (err) throw err;
          cb(null);
    });
}, function (cb){

for (var i=0; i<req.body.numBooks;i++){
    dbinfo.create({
        numBooks: i+1,
        done: false
    });

};cb(null)

}, function (cb){
    dbinfo.find({},function(err,result){
        if (err)
            res.send(err);
        res.json(result);
        console.log(result);
        cb(null);
    });
}], function(error, results) {

});
});

In my front-end, I want to input my number of books and then according to the number of books, the list will appear.Example below:-

Number of books:-5(numBooks in the codes) [SUBMIT BUTTON]
Book number 1:
Book number 2:
Book number 3:
Book number 4:
Book number 5:

The codes above do not work but if I press F5 to refresh the page. It will give me the right front end.

thanks to help


Solution

  • You have a race condition in your second function call where you are trying to .create() your models. .create() takes a second parameter for a callback.

    It should look something like this. Your .series() function should not advance until all models have been properly created.

    var bookNum = [];
    for (var i = 0; i < req.body.numBooks; i++) {
      bookNum.push(i+1)
    }
    async.map(bookNum, function(num, cb) {
      dbinfo.create({
        numBooks: i+1,
        done: false
      }, cb);
    }, cb);
    

    To write the entire code for you...

    app.post('/api/infosave', function(req, res, next) {
        async.waterfall([
            function(cb) {
                dbinfo.remove({}, cb);
            },
            function(ignore, cb) {
                var bookNum = [];
                for (var i = 0; i < req.body.numBooks; i++) {
                  bookNum.push(i+1)
                }
                async.map(bookNum, function(num, cb) {
                  dbinfo.create({
                    numBooks: i+1,
                    done: false
                  }, cb);
                }, cb);
            }
        ], function(err, results) {
            if (err) return next(err);
            res.json(results);
        })
    });