1

Just started working with Nodejs and facing this issue while pushing the array as a response in the below code. I know this is happening because of the asynchronous nature of Nodejs, tried to apply async as well but did not get the desired result. Could someone let me know the fix of this code:

array = [];
  var company = companySchema.Company;
  company.findOne({_id: companySchema.objectId(req.tempStore.companyId)}, function (err, comp) {
    if (err) {
      console.log(err);
     }
     else {
       var i;
       var length = comp.events.length;
       var dataset = datasetSchema.dataset;
       for (i = 0; i < length; i++) {
         dataset.find({companyId:comp.events[i]}, function (err,data) {
           if (err) {
             console.log(err);
           }
           else {
             array.push(data);
           }

             console.log("array-----"+array);  // prints array here
         });
       }
     }
            console.log("array-----"+array);    // array is empty hence causing empty response
             res.response.data = array;
              next();
  });

1 Answer 1

2

You can use mongoDB $in clause for this task:

var company = companySchema.Company;
company.findOne({_id: companySchema.objectId(req.tempStore.companyId)}, function (err, comp) {
    if (err) {
        console.log(err);
    } else {
        var dataset = datasetSchema.dataset;
        dataset.find({companyId : {$in : comp.events}}, function (err, docs) {
            if (err) {
                console.log(err);
            } else {
                console.log("array: " + docs);  // prints array here
                res.response.data = docs;
                next();
            }
        });
    }

});
Sign up to request clarification or add additional context in comments.

1 Comment

Ohhh. didn't think this way. Thanks a lot @Kairat

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.