【问题标题】:Trigger a function when a new document is created is not working创建新文档时触发功能不起作用
【发布时间】:2019-07-09 06:16:35
【问题描述】:

我已尝试使用 Cloud Functions 的增量计数器示例 (https://github.com/firebase/functions-samples/tree/master/child-count),它引用实时数据库,但不引用 Firebase Firestore。

我正在关注 Firestore 文档并尝试了一些更改。仍然面临问题并且无法为 firestore 新文档运行此代码。第一次写云函数,不知道写对了。

   exports.countlikechange = functions.database.ref('/posts/{postid}/likes/{likeid}').onWrite(
async (change) => {
  const collectionRef = change.after.ref.parent;
  const countRef = collectionRef.parent.child('likes_count');

  let increment;
  if (change.after.exists() && !change.before.exists()) {
    increment = 1;
  } else if (!change.after.exists() && change.before.exists()) {
    increment = -1;
  } else {
    return null;
  }

  // Return the promise from countRef.transaction() so our function
  // waits for this async event to complete before it exits.
  await countRef.transaction((current) => {
    return (current || 0) + increment;
  });
  console.log('Counter updated.');
  return null;
});

我想更新父文档中的计数。

【问题讨论】:

    标签: node.js google-cloud-firestore google-cloud-functions


    【解决方案1】:

    您应该查看documentation for Firestore triggers。您正在编写的是实时数据库触发器,因为函数声明是functions.database。你会想改用functions.firestore。您还使用实时数据库 API 而不是 Firestore API。您使用 Firestore 的最终解决方案看起来与您现在拥有的几乎完全不同。

    【讨论】:

    • 也许他在询问如何使用 firestore 实现这一点的代码。
    猜你喜欢
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 2020-03-28
    • 2016-10-09
    • 1970-01-01
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多