【问题标题】:Remove value from database using Cloud Functions使用 Cloud Functions 从数据库中删除值
【发布时间】:2017-06-28 19:24:14
【问题描述】:

我有以下数据结构:

如何使用云函数完全删除“天”?

我当前的代码:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

     exports.deleteOldItems = functions.database.ref('/path/to/items/{pushId}')
    .onWrite(event => {
      var ref = event.data.ref.parent; // reference to the items
      var now = Date.now();
      var cutoff = now - 2 * 60 * 60 * 1000;
      var oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff);
      return oldItemsQuery.once('value', function(snapshot) {
        // create a map with all children that need to be removed
        var updates = {};
        snapshot.forEach(function(child) {
          updates[child.key] = null
        });
        // execute all updates in one go and return the result to end the function
        return ref.update(updates);
      });

functions.database.ref('/days').remove(); // <- /days doesn't get removed

    });

【问题讨论】:

    标签: javascript node.js firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    在调用 remove 之前,您正在从函数返回。试试:

      return oldItemsQuery.once('value', function(snapshot) {
        // create a map with all children that need to be removed
        var updates = {};
        snapshot.forEach(function(child) {
          updates[child.key] = null
        });
        // execute all updates in one go and return the result to end the function
        return ref.update(updates);
      }).then(function() {;
        return functions.database.ref('/days').remove();
      });
    

    【讨论】:

    • 有什么不好的?您收到错误消息吗?
    • @FrankvanPuffelen 我没有收到错误消息。 'days' 不会被删除。
    • 更新了我的答案。您在调用 remove() 之前返回
    • 成功了!但是,我如何删除 /days 只有当它有超过 1 个孩子? @FrankvanPuffelen 我必须做出哪些改变?
    • 您必须修改代码以包含该条件。我建议从 Cloud Functions 退后几步,首先尝试使用常规的 Firebase JavaScript SDK 进行相同的工作。一个 jsbin 如果我最喜欢写这样的 sn-ps 的地方。一旦你让它在那里工作,就很容易将它传输到云函数中并进行部署。