title: Access a cloud firestore document within a cloud function
body: <p>Within my Google Firebase Firstore database I would like to gather aggregative data such as how many documents a collection has. Since Firestore does not provide aggregative queries I'm attempting to write a cloud function that will increment a field every time a document is added to the database which will contain the number of documents a collection has.</p>
  
  <p>The problem I'm having is I cannot for the life of me figure out how to grab documents from Firestore within a cloud function using nodejs.</p>
  
  <p>Here's what I'm doing:</p>
  
  <p>At the top of my <code>index.js</code> file I configure the admin SDK and what have you like this:</p>
  
  <pre><code>const functions = require('firebase-functions');
  const admin = require('firebase-admin');
  admin.initializeApp(functions.config().firebase);
  </code></pre>
  
  <p>Then for my cloud function I do this:</p>
  
  <pre><code>exports.createPost = functions.firestore
    .document('posts/{post_id}')
    .onCreate(event =&gt; {
  
      // Get the post object
      var post = event.data.data();
  
      var senderID = post["sender_id"]; // This is not null
  
      // Access to user's document and the main ledger document
      const userDocRef = admin.database().ref('/users').orderByChild("user_id").equalTo(senderID).once('value')
      const ledgerDocRef = admin.database().ref('/posts/ledger').once('value');
  
      return Promise.all([userDocRef, ledgerDocRef]).then(snapshot =&gt; {
  
          const user = snapshot[0].val();
          const ledger = snapshot[1].val();
  
          console.log("user =&gt; "+user); // Logs: user =&gt; null
          console.log("ledger =&gt; "+ledger); // Logs: ledger =&gt; null
  
          const userPostCount = user["user_name"];
          const globalPostCount = ledger["global_post_count"] + 1;
  
          const userUpdate = user.update({"post_count" : userPostCount});
          const ledgerUpdate = ledger.update({"global_post_count" : globalPostCount});
  
          return Promise.all([userUpdate, ledgerUpdate]);
      });
  });
  </code></pre>
  
  <p>I end up with the error:</p>
  
  <blockquote>
    <p>TypeError: Cannot read property 'global_post_count' of null
        at Promise.all.then.snapshot</p>
  </blockquote>
  
  <p>Which I figure means something is wrong with my query but I don't know what. Both the <code>users</code> and <code>posts</code> are root level collections.</p>
  
  <p>Im also getting a warning that says:</p>
  
  <blockquote>
    <p>Billing account not configured. External network is not accessible and
    quotas are severely limited.</p>
  </blockquote>
  
  <p>From what I've read online, I don't think that effects it but I thought it was worth noting.</p>
  
  <p>Please help.</p>