如何在文档中创建自定义变量的侦听器

时间:2019-08-05 07:46:02

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

当文档内部发生任何更改时,此代码将更新,但我希望更改自定义变量而不是任何变量。

例如,我想在更改Score变量时调用此函数。

exports.updateUser = functions.firestore.document('Test/uhfL5NE199eYTGyfSH1srtrtee').onUpdate((change, context) => {
  const washingtonRef = admin.firestore().collection('Test').doc('uhfL5NE199eYTGyfSH1srtrtee');
  return washingtonRef.update({Counts:admin.firestore.FieldValue.increment(1)});
});

1 个答案:

答案 0 :(得分:1)

这是不可能的。使用Cloud Function和Firestore,如果文档已经存在并且任何值已更改(请参见https://firebase.google.com/docs/functions/firestore-events),就会触发.onUpdate()。

您可以做的是使用两个快照,它们分别表示触发事件之前 之后的数据状态,这些快照存在于change对象中,如下:

exports.updateUser = functions.firestore.document('Test/uhfL5NE199eYTGyfSH1srtrtee').onUpdate((change, context) => {

  const newValue = change.after.data();
  const previousValue = change.before.data();

  //Check if the Score field has changed
  if (newValue.Score  !== previousValue.Score) {

    //Score field has changed! -> Do whatever you want

  } else {
     //End the Cloud Function
     return false;
  }


});