@lyjackal helped me here (NodeJS Asynchronous and Recursive) to solve recursive for finding children.
I am still trying to get my head around nodejs promises. I have a similar problem as the previous post, but slightly different. I feel this code is close, but it doesn't work.
I have an Assignment, and Assignment has a reference to a Path. That Path, and all paths, may or may not have a parent Path. I need this code, to find the path of paths as it were, and just stack a few attributes of each path in an array. The array at the end would look like this:
[ [0]=>{field: name, match: match_type, value:value},
[1]=>{field: name, match: match_type, value:value},
...]
The order of the array doesn't even matter. Here is the code with Promises... that is broken:
exports.assignRecursiveQuery = function(req,res) {
var methods = {}
var query_to_save = []
methods.recursiveParents = function(path) {
return new Promise(function(resolve, reject) {
Path.find({
_id: path.parent
}).exec(function(err, parentPaths) {
Promise
.all(parentPaths.map(function(parentPath) {
return methods.recursiveParents(parentPath)
}))
.then(function(promisedPaths) {
return resolve(promisedPaths);
});
});
});
}
Path.find({_id: req.assignment.path_end}).exec(function(err,lastPaths) {
//add first query rule
console.log(lastPaths[0]);
query_to_save.push({field:lastPaths[0].field.api,match:lastPaths[0].match,value:lastPaths[0].value})
Promise.all(lastPaths.map(function(path) {
return methods.recursiveParents(path);
})).then(function(resolvedPaths) {
for( var x=0; x<resolvedPaths.length; x++ ) {
console.log(resolvedPaths[x])
query_to_save.push({field:resolvedPaths[x].field.api,match:resolvedPaths[x].match,value:resolvedPaths[x].value});
}
console.log(query_to_save);
res.jsonp(req.assignment)
});
});
}