title: Firebase Query on Date Range on basis of Child Node
body: <p>I'm trying to generate a weekly report from some data in Firebase database and using Firebase cloud function for that purpose. <em>Timestamp actually exists in child nodes.</em> However, I'm unable to fetch any data.</p>
  
  <p>My DB structure is as follows :</p>
  
  <pre><code> {
     "threads" : {
        "228440-1704-4bba-87d7-27327" : {
           "messages" : {
             "8c98a76c-4456-4326-8e18-6d036b40bfa4" : {
                "time" : 1519997400,
                "payload": "someData"
              }, 
              "898376c-4456-4326-8e18-6deb4wr0bfa4" : {
                "time" : 1517174415302,
                "payload": "someData"
               }
            },
        "details" : {
          "created_At": 1514134435602 
          }
      }  
  </code></pre>
  
  <p><strong>Fetch data on basis of detail node:</strong>
  I'm trying to fetch threads where <code>threads/details/created_at</code> exists in my date range (say last week). </p>
  
  <p><strong>Fetch data on basis of messages node:</strong> Apart from this, in another query, i want to fetch all messages (in different threads) for last week. I guess I'll have to fetch threads even in this scenario with some thing like:</p>
  
  <pre><code>//fetch threads where message.time exists in last week
  </code></pre>
  
  <p>I'm using Firebase cloud functions, and my code is as:</p>
  
  <pre><code>exports.generateReportFromThreads = functions.https.onRequest((req, res) =&gt; {
  
      var ref = admin.database().ref('threads');
      var startingTime = new Date('Mon, 25 Dec 1995 13:30:00 GMT').getUnixTime();
      var currentDate = new Date('Fri, 2 Mar 2018 13:30:00 GMT').getUnixTime();
  
      return ref.orderByChild('details/created_at').startAt(startingTime).endAt(currentDate).once("value", (threadSnapshot) =&gt; {
  
        var numberOfThreads = threadSnapshot.numChildren()
        var totalMessages = 0
  
         threadSnapshot.forEach((snapshot) =&gt; {
  
          var ref = snapshot.child('messages')
           var messagesPerThread = ref.numChildren()
           totalMessages = totalMessages + messagesPerThread
  
  
        res.send(`
            &lt;!doctype html&gt;
            &lt;html&gt;
                &lt;body&gt;
                 &lt;p&gt;Total number of threads = ${numberOfThreads}&lt;/p&gt;
                 &lt;p&gt;Total messages = ${totalMessages}&lt;/p&gt;
                &lt;/body&gt;
            &lt;/html&gt;`
        );
     });
  });
  </code></pre>
  
  <p><strong>I've applied indexes in my DB as:</strong></p>
  
  <p><a href="https://i.stack.imgur.com/X3MpM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X3MpM.png" alt="enter image description here"></a></p>