【问题标题】:When using the onUpdate function in Firebase, how do I retrieve the record that has been updated?在 Firebase 中使用 onUpdate 函数时,如何检索已更新的记录?
【发布时间】:2018-11-29 00:40:48
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    传递给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
    })
    

    【讨论】:

    • 谢谢!那么常量“之前”和“之后”是否可以像普通对象一样对待?例如:console.log(before.bidAmount)(如果bidAmount是数据库中记录的一个字段)
    • 点击进入我提供给 DataSnapshot 对象的 API 文档链接。您可以使用 val() 方法从快照中获取原始数据。
    • 谁能提供已接受答案的更新链接?所有链接都已损坏 (404) @DougStevenson
    【解决方案2】:

    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) 触发器。根据文档,已更新的记录似乎作为第一个参数传入。我将从在回调函数中记录参数对象开始。

    文档里面的例子是:

    // 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);
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      相关资源
      最近更新 更多