I have a an array of objects and each object contains another array. Value of Each object in the arrays is an id that needs to be replaced by the Name in the corresponding document with _id==id in the collection. In this particular case the async nature of NodeJS has been a pain and keeping track of whether the data of all the objects in the outer and inner arrays has been updated by finding them from the collection.
The easiest but dirty way of achieving this is with BLOCKING mongoose.find() call that would not execute the preceding statements until the data in the current object has been updated.
How can I achieve this?
Write now I am trying to do it like this but it's not working.
function getIDForName(name, callBackMethod) {
var _id = null;
var breakTheLoop = false;
const thread = spawn(function() {
// Everything we do here will be run in parallel in another execution context.
// Remember that this function will be executed in the thread's context,
// so you cannot reference any value of the surrounding code.
CircleTimeSong.getCircleTimeSongModelObject().find({songName:name}, function(err, foundData) {
console.error("callback");
if (err) {
console.error("error in getIDForName CircleTimeSongController.js: ", err);
//callBackMethod(null);
breakTheLoop = true;
}
console.log("found data length: ", foundData.length);
if (foundData != null && foundData.length > 0) {
console.log("doku 3", foundData[0]._id);
_id = foundData[0]._id;
breakTheLoop = true;
}
//callBackMethod(_id);
});
});
while(true) {
//console.log("in loop");
if(breakTheLoop)
break;
}
thread.kill();
return _id;
}