首页 文章

如何在Firebase Cloud功能中执行类似'child-added'事件的操作?

提问于
浏览
1

我需要使用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 orderByKey或orderByChild,并使用 limitToLast(1)

或者,使用Sets来执行 snapshot.after.val()snapshot.before.val() 上的Set Difference operation工作?

2 回答

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

相关问题