【问题标题】:Removing item ref from Firebase Cloud Functions从 Firebase Cloud Functions 中删除项目 ref
【发布时间】:2017-04-29 12:48:00
【问题描述】:

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

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

    });

语句“it.ref.remove()”运行但不删除子项。有什么问题?

更新

我不知道为什么,但是使用 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

【问题讨论】:

  • 有什么不好的?它不会被调用吗?添加日志语句可能有助于确定这一点。 if 语句的计算结果是否为 false?我们很难为您远程调试您的功能。如果您首先使用 Firebase Admin SDK 将代码编写为本地 node.js 脚本并确保它在那里工作,可能会更容易。您的代码与数据库之间的交互在本地与远程相同,只是在 Cloud Functions 环境中触发器不同。
  • 语句 it.ref.remove() 没有删除项目。有什么问题?

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


【解决方案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);

});

【讨论】: