title: Best way to process results of multiple, sequential, dependent mongo queries in NodeJS
body: <p><strong>High level</strong></p>
  
  <p>I'm new to JS and Node. I'm working on an API endpoint that should return a status value. To compute the status value I need to make two sequential mongo queries where the second set of queries depend on the first query. The second set of queries will give me a status for each value found in the first query, of which I will pick one based on some logic. What is the best way to do it in NodeJS?</p>
  
  <p><strong>Specifics</strong></p>
  
  <p>Here are parts of my first attempt.</p>
  
  <pre><code>function getItemStatus(key, value, callback) {
          MongoClient.connect(mongo_url, function(err, db) {
              if (err) { return console.dir(err); }
              db.collection('status', function(err, coll) {
                  if (err) { return console.dir(err); }
                  coll.distinct("_id.metric", function(err, metrics) {
                      if (err) { return console.dir(err); }
                      console.log('metrics : ', metrics);
                      _.foreach(metrics, function(metric) {
                          var query = {"_id": {
                              "$gte" : {key: key, value: value, created: new Date("1800-01-01T00:00:00"), metric : metric},
                              "$lte" : {key: key, value: value, created: new Date("2100-01-01T00:00:00"), metric : metric}}};
                          coll.find(query, {sort: {"_id.created": -1}, limit: 1})
  </code></pre>
  
  <p>I make a connection, query for a set of metric values using a distinct query. For each metric I then want to ask for the latest status. Ideally I'd like to have the entire set of statuses so that I could write a function taking this set and deciding on which status will be returned. My problem is passing the statuses back "up the chain" so that I can process the set of statuses.</p>
  
  <p>In a synchronous situation I would simply write something like this</p>
  
  <pre><code>val metrics = getDistinctMetrics(key, value)
  val statuses = metrics.map(getStatusForMetric)
  val status = filterStatuses(statuses)
  </code></pre>
  
  <p>How can I accomplish this in JavaScript/NodeJS?</p>
  
  <p><strong>UPDATED</strong> to highlight the fact that the first queries will trigger <em>several</em> queries in the second step,  i.e. one for each result found by the first query.</p>