如何仅在更新字段时触发 Firebase 云功能?

Dew*_*wey 10 node.js firebase google-cloud-functions google-cloud-firestore

我想仅在更新 firestore 文档的特定字段时触发云功能。我不想在每次更新文档时触发它,而不管哪个字段。是否可以?

例如:

exports.onAvatarUpdated = functions.firestore.document('users/{userId}/avatarUrl')
  .onUpdate(change => { 
  // do something here
});
Run Code Online (Sandbox Code Playgroud)

Dou*_*son 5

目前没有针对特定字段的触发器。您只能在对文档进行任何更改时触发,如果您想知道特定字段是否发生更改,则必须检查更改对象以找出答案。

如果您希望能够表达仅关注特定领域的功能,您始终可以提交功能请求

  • @Curse 数据建模的方式在两个数据库之间根本不同。如果您需要在单个字段上触发,您始终可以使用单个字段制作单个文档,并将其他所有内容放在单独的文档中。这是一个有效的数据设计决策。文档不必是给定实体的唯一数据源。 (3认同)

Lik*_*777 5

我将从这里更改 Firebase 本机手动代码:

exports.updateUser = functions.firestore
.document('users/{userId}')
.onUpdate((change, context) => {
  // Get an object representing the document
  // e.g. {'name': 'Marie', 'age': 66}
  const newValue = change.after.data();
  const newFieldValue = newValue.field;

  // ...or the previous value before this update
  const previousValue = change.before.data();
  const previousFieldValue = previousValue.field;


  if (previousFieldValue!== newFieldValue) 
       {      // perform desired operations ... }
});
Run Code Online (Sandbox Code Playgroud)