0

Here i am iterating an array and save it i database. After completion of iteration, i have to send the response to front end only once(not inside the loop), here is my code. I am declaring a boolean called create quest to false; after iterating all the element in array i have to return response by checking boolean if true? But before completing the loop, below if condition is executing/ so that time boolean is still false; after that line number 9 will start executing.

              createQuest = false;
              questionList.forEach(element => {
                var quest = new Questionnaire({
                    _id: new mongoose.Types.ObjectId(),
                    question: element.question,
                    blockId: blockId
                });
                quest.save((err1, doc1) => {
9:                    if(!err1){
                       createQuest = true;
                    }else{
                        res.send({'message':'failed'});
                    }
                })
            });
            if(createQuest == true){
              res.send({'message':'success'});
            }

3 Answers3

0

BY the way you are implemented you can do the following:

  var counter = 0;
  questionList.forEach(element => {
    var quest = new Questionnaire({
        _id: new mongoose.Types.ObjectId(),
        question: element.question,
        blockId: blockId
    });
    quest.save((err1, doc1) => {
         if(!err1){
           counter++;
        }else{
           counter++;
            //res.send({'message':'failed'});
        }
    })
 if(counter == questionList.length) {                
  res.send({'message':'success'});            
 }
});

Also you can use promise.all to implement this.

Subburaj
  • 5,114
  • 10
  • 44
  • 87
0

If your purpose is to save all the quests and then send the response then this is what you can do:

        let createQuest = false;
        let quests = questionList.filter(element => {
            return {
                _id: new mongoose.Types.ObjectId(),
                question: element.question,
                blockId: blockId
            });
        });
        Questionnaire.create(quests, function(err) {
            if(err)
               return res.send({'message':'failed'});
            res.send({'message':'success'});
        });
Yogeshwar Singh
  • 1,245
  • 1
  • 10
  • 22
0

Run multiple parallel task for by iterating over array ( any collection ) and once all of them are finish execute something else Consider a scenario where you need to Update multiple. You have questions pushed in an array and you want to execute all function dependent of each other.

Solution : Use async.eachSeries() Here is code to explain same

var async = require('async');

async.eachSeries(questionList,function(element ,eachCb) {
   var quest = new Questionnaire({
        _id: new mongoose.Types.ObjectId(),
        question: element.question,
        blockId: blockId
    });
    quest.save((err1, doc1) => {
         if(!err1){
           counter++;
        }else{
           counter++;  
    return eachCb(err1);
        }
    eachCb();
    })
},function(err,data) {
    if(err){
    console.log(err);
    }
  // Once all done, comes here.
});

For Reference Check with

https://codeforgeek.com/asynchronous-programming-in-node-js/

https://dzone.com/articles/how-to-interact-with-a-database-using-the-async-mo

async.eachSeries in node.js

(OR)

Here are both way of saving data with insertMany and save

1) Mongoose save array of documents with insertMany in bulk db.collection.InsertMany()

var Questionnaire= mongoose.model('Potato', Questionnaire);

 write this api in routes directory 
router.post('/addDocuments', function (req, res) {
    const data = [/* array of object which data need to save in db */];

    Questionnaire.insertMany(data)  
    .then((result) => {
            console.log("result ", result);
            res.status(200).json({'success': 'new documents added!', 'data': result});
    })
    .catch(err => {
            console.error("error ", err);
            res.status(400).json({err});
    });
})
Mohan Ohanra
  • 101
  • 3