Firebase云功能对象更新创建递归

问题描述 投票:1回答:2

我的应用程序具有简单的云功能,可以跟踪创建/更新的时间戳。它看起来像这样:

export const objectChanges = functions
  .firestore
  .document('objects/{id}')
  .onWrite(event => {
    const patch: {created_at?: string, updated_at: string} = {
      updated_at: <string> event.timestamp
    };

    if (!event.data.previous) {
      patch.created_at = event.timestamp;
    }

    return event.data.ref.set(patch, {merge: true});
  });

只要我上传此功能并在列表中创建/修改对象,它就会不断开始记录updated_at。我猜它正在检测它本身对updated_at字段所做的更改。考虑到文档显示了这种更新的一个示例,这种行为让我感到困惑。

https://firebase.google.com/docs/functions/firestore-events#writing_data

我缺少一个细微差别,或者这是一个Firestore错误?

javascript node.js firebase google-cloud-functions google-cloud-firestore
2个回答
1
投票

如果您检查文档中给出的示例,则会检查一个条件以查看name是否已更改。如果是,则仅执行以下代码。如果它没有变化,它只是returns,像这样:

// We'll only update if the name has changed.
// This is crucial to prevent infinite loops.
if (data.name == previousData.name) return;

因此,在您的情况下,您还需要检查对象的实际数据(除了updated_at之外的所有字段)是否都已更改。如果没有别的(除了updated_at)改变了,你应该简单地退出该功能。


1
投票

请特别注意您引用的文档示例代码部分:

// We'll only update if the name has changed.
// This is crucial to prevent infinite loops.
if (data.name == previousData.name) return;

您需要找到一种方法来检测函数执行的更新何时触发同一位置的后续更新。

© www.soinside.com 2019 - 2024. All rights reserved.