首页 > 解决方案 > Firebase Cloud Functions 在写入后立即删除数据

问题描述

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

这是云函数代码:

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/"
      }
    }
  }
}

我已经多次搜索这个解决方案,但没有从任何地方得到它。谁能帮帮我吗。

标签: androidnode.jsfirebasefirebase-realtime-databasegoogle-cloud-functions

解决方案


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

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

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

推荐阅读