Node.js 当创建的新文档不工作时触发函数

Node.js 当创建的新文档不工作时触发函数,node.js,google-cloud-firestore,google-cloud-functions,Node.js,Google Cloud Firestore,Google Cloud Functions,我用云函数尝试了一个增量计数器示例(),它引用的是实时数据库,但不是Firebase Firestore 我正在跟踪firestore文档并尝试了一些更改。仍然面临问题,无法为firestore新文档运行此代码。我第一次写云函数,我不确定我写的是否正确 exports.countlikechange = functions.database.ref('/posts/{postid}/likes/{likeid}').onWrite( async (change) => { con

我用云函数尝试了一个增量计数器示例(),它引用的是实时数据库,但不是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;
});

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

您应该查看。您正在编写的是一个实时数据库触发器,因为函数声明是
functions.Database
。您将希望改用
函数.firestore
。您还使用实时数据库API而不是Firestore API。您使用Firestore的最终解决方案看起来几乎与您现在的解决方案完全不同。

也许他要求提供代码,说明如何使用Firestore实现此功能。