从Firebase云功能中删除项目参考

时间:2017-04-29 12:48:00

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

我需要从列表中删除一个项目,但以下代码不起作用:

exports.removeOldItems = functions.database.ref('/chat/usersOnline/{userId}')
    .onWrite(event => {
      const snap = event.data;
      if (!snap.exists()) return;

      snap.forEach(it => {                                                                                 
        if ( condition ) {
          it.ref.remove();   <---- THIS NOT WORK
        }
      })

    });

陈述&#34; it.ref.remove()&#34;运行但不删除子项。可能有什么不对?

更新

我不知道为什么,但使用parent.once(...)解决了这个问题:

exports.removeOldItems = functions.database.ref('/chat/usersOnline/{userId}')
    .onWrite(event => {
      if (!event.data.exists()) return;
      const parentRef = event.data.ref.parent;

      return parentRef.once('value').then(users => {
        users.forEach(function(tabs) {                               
          tabs.forEach(instance => {                                  
            if ( condition ) {                                          
              instance.ref.remove();
            }
          })
        });
      });

    });

我使用以下示例作为指南:https://github.com/firebase/functions-samples/blob/master/limit-children/functions/index.js

1 个答案:

答案 0 :(得分:1)

这可能会发生,因为你没有回复承诺。 尝试这样的事情。

exports.removeOldItems = functions.database.ref('/chat/usersOnline/{userId}')
.onWrite(event => {
  const snap = event.data;
  var itemstoremove = [];
  if (!snap.exists()) return;

  snap.forEach(it => {                                                                                 
    if ( condition ) {
      itemstoremove.push(it.ref.remove());   <---- THIS NOT WORK
    }
  })
return Promise.all(itemstoremove);

});
相关问题