【问题标题】:Delete older firebase data [duplicate]删除旧的firebase数据[重复]
【发布时间】:2018-07-12 21:24:49
【问题描述】:

我想删除超过 2 小时的数据。我尝试了另一个 SO 答案,但没有解决我的问题。

https://stackoverflow.com/a/32012520/2872091

现在,让我展示一下我的代码和 Firebase 结构

Firebase 结构:

Index.js:

const functions = require('firebase-functions');
exports.deleteOldItems = functions.database.ref('Room/English/{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('time').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);

  });
});

然后,我将此 js 文件部署到我的 firebase。

firebase deploy --only functions

部署成功,终端提示“部署完成!”。我可以在 Firebase 函数中看到 deleteOldItems 函数。

结果,我的结构和代码是这样的。当新数据添加到 Room/English 节点时,没有任何变化。此节点中的数据(超过 2 小时)不会被删除。我该如何解决这个问题?我的错误是什么?

【问题讨论】:

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


【解决方案1】:
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);
  });
});

【讨论】:

  • 你为什么喜欢这个?错误的答案!我的孩子是时间,除了我认为,我的路径是 Room/English/{pushId}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-23
  • 1970-01-01
  • 1970-01-01
  • 2021-01-20
  • 2021-02-23
  • 2020-08-17
相关资源
最近更新 更多