Firebase Cloud Functions正在写入后立即删除数据

时间:2019-08-11 14:15:56

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

我已经实现了Firebase Cloud Functions,以从Firebase数据库中删除数据。我的每个孩子都有一个时间戳,所以我想删除早于2小时的数据,而不是2小时后删除,而是在写入数据库后立即删除孩子。

这是Cloud Functions代码:

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

// Cut off time. Child nodes older than this will be deleted.
const CUT_OFF_TIME = 2 * 60 * 60 * 1000; // 2 Hours in milliseconds.

/**
 * This database triggered function will check for child nodes that are older than the
 * cut-off time. Each child needs to have a `timestamp` attribute.
 */
exports.deleteOldItems = functions.database.ref('/database/{pushId}').onWrite(async (change) => {
  const ref = change.after.ref.parent; // reference to the parent
  const now = Date.now();
  const cutoff = now - CUT_OFF_TIME;
  const oldItemsQuery = ref.orderByChild('timeStamp').endAt(cutoff);
  const snapshot = await oldItemsQuery.once('value');
  // create a map with all children that need to be removed
  const updates = {};
  snapshot.forEach(child => {
    updates[child.key] = null;
  });
  // execute all updates in one go and return the result to end the function
  return ref.update(updates);
});
{
  "app_title" : "app",
  "database" : {
    "-Lm3gJ16yk5ZNdt8z2PJ" : {
      "message" : "ok",
      "timeStamp" : "1565594302830",
      "userModel" : {
        "email" : "abcd@yahoo.com",
        "name" : "Microsoft",
        "photo" : "https://graph.facebook.com/"
      }
    }
  }
}

我已经多次搜索该解决方案,但是没有从任何地方获得它。 谁能帮我。

1 个答案:

答案 0 :(得分:1)

您的时间戳记存储为字符串,而代码假定其为数字。我强烈建议修复写入时间戳的代码,以便将其存储为数字。

但是与此同时,您可以使用以下命令查询字符串:

const oldItemsQuery = ref.orderByChild('timeStamp').endAt(""+cutoff);