【问题标题】:Delete Firebase Child after 10 hours10 小时后删除 Firebase Child
【发布时间】:2018-03-01 09:31:33
【问题描述】:

我想要一个删除 10 小时大的孩子的函数。到目前为止我有这段代码,但是如果我将它部署到 Firebase 云函数,它会立即从数据库中删除所有数据。我不确定我做错了什么。请帮忙!

exports.deleteOldItems = functions.database.ref('Rollerbanken/{pushId}')
.onWrite(event => {
  var ref = event.data.ref.parent; // reference to the items
  var now = Date.now();
  var cutoff = now - 10 * 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);
  });
});

我的 Firebase 数据库结构:

{
  "Rollerbanken" : {
    "-Ku_Ywh8wElDdwNqa0KW" : {
      "Extrainformatie" : "",
      "Latitude" : "51.8306880305073",
      "Longitude" : "5.90483402833892",
      "Staater" : "Staat er nog steeds",
      "Staaternietmeer" : "",
      "Stad" : "Nijmegen",
      "Tijd" : "19:50",
      "TijdControle" : "19:50",
      "TijdControleniet" : "",
      "TypeControle" : "Rollerbank",
      "TypeControle2" : "Rollerbank",
      "postKey" : "-Ku_Ywh8wElDdwNqa0KW",
      "timestamp" : 1506016223000
        }
      }
    }

【问题讨论】:

  • 你能给我们看一个存储在Rollerbanken/{pushId}的项目的例子吗?
  • 当然,我编辑了!

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


【解决方案1】:

这就是我的 24 小时编码方式。

 exports.deleteOldItems = functions.database.ref('/notification/{user_id}/{notification_id}').onWrite((change) => {

    const ref = change.after.ref.parent; // reference to the parent

    // For easier cross browser solution, get old time like this
    const yesterday = Date.now() - 86400000; // that is: 24 * 60 * 60 * 1000
    const oldItemsQuery = ref.orderByChild('time').endAt(yesterday);

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

编码愉快!

【讨论】:

    【解决方案2】:

    您的代码中有ref.orderByChild('timestamp'),但您的数据中没有timestamp 字段。这被解释为具有 null 时间戳,实际上它在 Firebase 施加的 ordering 中具有最高优先级。因此,您的所有数据节点都会在指定的 cutoff 之前排序,并被删除。

    要解决这个问题,您需要将timestamp 字段添加到您的架构中。

    【讨论】:

    • 我的结构中现在有时间戳:"timestamp": ServerValue.timestamp() 但它仍然无法正常工作!
    • 我的日志说它完成了'ok'。所以我不明白发生了什么?
    猜你喜欢
    • 2018-04-12
    • 2019-10-12
    • 1970-01-01
    • 2019-10-01
    • 2020-12-06
    • 2017-08-11
    • 1970-01-01
    • 2018-09-18
    • 2020-01-17
    相关资源
    最近更新 更多