Greetings everyone,
I find myself stuck in a callback nightmare while attempting to retrieve basic values from a Mongoose count by passing a {query}. Although I can access the value and see it fine in the console within the callback, extracting it from an asynchronous callback setup is proving to be quite challenging.
Using Node.js and Express, I am trying to accomplish simple tasks such as fetching a count of a specific number from my Model, 'Job', with the aforementioned query.
I have a similar situation that works in one instance of a router.get, where I am able to write to a variable outside the callback parent function. Here's an example:
router.get('/repairmanager', ensureAuthenticatedAdmin, function(req, res) {
var list = []; // The list populates successfully even within the Job.find callback nest hole
if(filter == 'userid' && query != "" || null){
Job.find( {'userid' : new RegExp('^'+query+'$', "i")} )
.then(function(doc){
doc.forEach(function(job){
list.push(job);
});
});
res.render('repairmanager', { history: { 'data': list}});
}
)};
The above code works well and the list array gets populated...
However, when I try to obtain another value from
function pendingCount(){
var test = null;
Job.count({'repairstatus': 'Pending Approval'}, function(err, cb){
test = cb;
console.log('test inside callback: ' + test);
});
console.log('test outside callback: ' + test);
return test;
};
I struggle to get the `test` variable to populate or return to the pendingCount() function at all.
I understand there is some complexity involved with asynchronous callback functions, but why is the `list` array visible and writable in the other Mongoose function, while not in this function where I'm trying to get a simple count of the query {"repairstatus": "Pending Approval"}?
Thank you for any helpful insights that can assist in resolving this issue.