我如何在Firebase Cloud功能中执行类似“添加子项”事件的操作?

时间:2018-07-01 19:34:15

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

我需要使用Cloud Functions从Firebase实时数据库中获取新推送的孩子的路径(/ foo)。

/foo --newpushKey - eeee - ffff --pushKey1 - cccc - dddd --pushkey2 - aaaa - bbbb

我只需要新添加的数据,

--newpushKey - eeee - ffff

我经历了https://firebase.google.com/docs/functions/database-events。如何仅从ref('/foo').onWrite(...)中获取新添加的Child?

或者,我应该使用Admin SDK通过/foo在时间戳值上查询limitToLast(1) orderByKey还是orderByChild吗?

或者,使用Sets在snapshot.after.val()snapshot.before.val()上进行类似Set Difference operation的工作吗?

2 个答案:

答案 0 :(得分:0)

您将要对新推送的对象使用onCreate,而不要对创建,更新或删除的对象触发onWrite

  

您可以通过以下方式将路径部分指定为通配符:   大括号;

您需要在数据库引用中使用通配符路径,如下所示:

exports.checkForNew = functions.database.ref('foo/{createdID}').onCreate((created_child, context) => {

//context.params.createdID to reference the ID of the created object in the database under 'foo'
//created_child.val() to reference any field values of the created objcet

});

答案 1 :(得分:0)

您走在正确的轨道上,您甚至自己找到了the relevant documentation ...在该页面上,查看最后一个示例,我已采用该示例并将其编辑为为您更清晰:

                                                     Notice this parameter?
                                                     This function will only fire on
                                                     the new data-node itself, not on
                                                     the parent node...
                                                              \/
                                                              \/
exports.makeUppercase = functions.database.ref('/messages/{pushId}')
    .onCreate( (change, context) => {

      // Since the function will only fire on the newly created node itself
      // the data that is 'after' the event will be your new data.
      // You can access the new data by calling:
      change.after.val()

      // From here you can do whatever actions you want with that data. 
      // You can access the {pushId} parameter with:
      context.params.pushId

    });