【问题标题】:Firebase cloud functionsFirebase 云功能
【发布时间】:2020-06-09 06:06:29
【问题描述】:

我正在使用 Firebase 云功能从另一个文档创建新文档

基本上,我在文档中有一个名为 reps {} 的 字段,它以 userId 作为键,int 作为值

我想检查 reps {} 中 值的 sum 是否大于 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);

通过这个查询,我得到了代表图,我如何计算所有值的总和 在地图内

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

【问题讨论】:

标签: javascript firebase google-cloud-firestore google-cloud-functions


【解决方案1】:

通过做

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

您正在查询一个文档,get() 方法返回一个用 DocumentSnapshot 解析的 Promise。

因此,做

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

【讨论】:

  • 是的,我刚刚想通了。谢谢你的回复。
  • 我尝试了你的代码,在 firebase 控制台中我得到了这个错误:TypeError: doc.get(...).forEach is not a function
  • 是的,看看更新,我的代码有错误!
【解决方案2】:

所以我只是想通了:

我使用 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;
      });
    }
  });

【讨论】:

    猜你喜欢
    • 2018-11-29
    • 2018-05-09
    • 2020-06-13
    • 2020-11-12
    • 2019-03-22
    • 2017-08-01
    • 2023-04-01
    • 2018-04-19
    相关资源
    最近更新 更多