javascript Firebase云函数

qlvxas9a  于 2023-05-27  发布在  Java
关注(0)|答案(2)|浏览(171)

我正在使用Firebase云函数从另一个文档创建新文档
基本上,我在一个名为reps {}的文档中有一个字段,它将userId作为Key,将int作为value**。
我想检查reps {}值的总和是否大于100(示例)。
我有一个onUpdate功能,工作完美,但我需要添加此功能。我试过这个:

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);

通过这个查询,我得到了reps map,我如何计算map中所有值****的总和

admin
  .firestore()
  .collection("posts")
  .doc(userId)
  .collection("userPosts")
  .doc(postId).get().then(function (doc)
  {
    if (doc.exists)
    {
      console.log(doc.get("reps"));
    }
  });
nlejzf6q

nlejzf6q1#

通过做

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

你正在查询一个文档,get()方法返回一个Promise,它使用DocumentSnapshot进行解析。
因此,做

doc['reps'].values

不起作用
您需要使用DocumentSnapshot的get()方法,如下所示:

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;
     });
  });
wr98u20j

wr98u20j2#

所以我就想明白了:
我使用了get()来获取我正在寻找的字段。
要计算
值的总和
我使用:
Object.keys(rep).forEach(function (values) { var value = rep[values]; repCount += value; });
下面是我的代码:

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;
      });
    }
  });

相关问题