在Firebase中使用onUpdate函数时,如何检索已更新的记录?

时间:2018-06-20 00:54:26

标签: javascript firebase firebase-realtime-database google-cloud-functions

在firebase上使用云功能时,通过onUpdate触发器,如何检索已更新的记录(换句话说,触发该功能的记录)?我正在使用JavaScript与Firebase数据库进行交互。

2 个答案:

答案 0 :(得分:3)

您的onUpdate处理函数传递的第一个参数是Change对象。该对象具有两个属性beforeafter,两个属性都是DataSnapshot对象。这些DataSnapshot对象描述了触发函数的更改前后的数据库内容。

exports.foo = functions.database.ref('/location-of-interest')
.onUpdate((change) => {
    const before = change.before  // DataSnapshot before the change
    const after = change.after  // DataSnapshot after the change
})

答案 1 :(得分:0)

每个https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder#onUpdate

onUpdate(handler) => function(functions.Change containing non-null functions.database.DataSnapshot, optional non-null functions.EventContext)

因此,我猜测您只需要将回调函数传递到onUpdate(callback)触发器中。根据文档,该记录的更新似乎将作为第一个参数传递。我将从记录回调函数中的arguments对象开始。

文档中的示例为:

// Listens for new messages added to /messages/:pushId/original and creates an
// uppercase version of the message to /messages/:pushId/uppercase
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
    .onCreate((snapshot, context) => {
      // Grab the current value of what was written to the Realtime Database.
      const original = snapshot.val();
      console.log('Uppercasing', context.params.pushId, original);
      const uppercase = original.toUpperCase();
      // You must return a Promise when performing asynchronous tasks inside a Functions such as
      // writing to the Firebase Realtime Database.
      // Setting an "uppercase" sibling in the Realtime Database returns a Promise.
      return snapshot.ref.parent.child('uppercase').set(uppercase);
    });