0
votes

I am using Firebase cloud function to create new document from another document.

Basically, i have a field in a document called reps {} that takes userId as Key and and int as value.

i want to check if the sum of the values in reps {} is greater than 100(example).

i have an onUpdate function that works perfectly but i need to add this feature. i tried this:

var count = 0;
admin.firestore()
  .collection("posts")
  .doc(userId)
  .collection("userPosts")
  .doc(postId).get().then(doc =>
  { 
    doc['reps'].values.forEach(val =>
    { 
      count += val;
     });
  });

  console.log(count);

With this query i get the reps map, How can i calculate the sum of all value inside a map:

admin
  .firestore()
  .collection("posts")
  .doc(userId)
  .collection("userPosts")
  .doc(postId).get().then(function (doc)
  {
    if (doc.exists)
    {
      console.log(doc.get("reps"));
    }
  });
2
I think you don't get documents directly from the above written query. See this: googleapis.dev/nodejs/firestore/latest/… - Umar Hussain
@UmarHussain, Thanks for your reply. So how shoul i write my query?? - Abdelbaki Boukerche

2 Answers

2
votes

By doing

admin.firestore()
  .collection("posts")
  .doc(userId)
  .collection("userPosts")
  .doc(postId).get()

you are querying one document and the get() method returns a Promise that resolves with a DocumentSnapshot .

Therefore, doing

doc['reps'].values

will not work.

You need to use the DocumentSnapshot's get() method, as follows:

admin.firestore()
  .collection("posts")
  .doc(userId)
  .collection("userPosts")
  .doc(postId).get().then(doc =>
  { 
    var respObj = doc.get('reps');
    Object.entries(respObj).forEach(([key, value]) => { 
      count += value;
     });
  });
0
votes

So i just figured it out:

i used get() to get the field i was looking for.

To calculate the sum of values i used:

Object.keys(rep).forEach(function (values) { var value = rep[values]; repCount += value; });

Here's my code:

await admin
  .firestore()
  .collection("posts")
  .doc(userId)
  .collection("userPosts")
  .doc(postId).get().then(function (doc)
  {
    if (doc.exists)
    {
      var rep = doc.get("reps");
      Object.keys(rep).forEach(function (values)
      {
        var value = rep[values];
        repCount += value;
      });
    }
  });