首页 > 解决方案 > Cloud Function 根据时间戳立即删除节点,而不是在两小时后删除(删除旧子节点不起作用)

问题描述

我正在尝试实现“delete-old-child-nodes”云函数示例(https://github.com/firebase/functions-samples/tree/master/delete-old-child-nodes)。当目录被写入时,它应该删除所有超过 2 小时的节点。但是,无论如何它只会删除所有节点。

我发现这篇 StackOverflow 帖子描述了同样的问题。但是,我相信原因是不同的。用户以秒为单位存储他的时间戳,而截止时间以毫秒为单位。在我的代码中,两者都以毫秒为单位。

这是当前的 index.js 代码,它与 Firebase 示例完全相同,只是我将时间戳称为“lastUpdated”而不是“timestamp”。

'use strict';

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

const CUT_OFF_TIME = 2 * 60 * 60 * 1000; 

exports.deleteOldItems = functions.database.ref('/decks/{pushId}').onWrite(async (change) => {
  var ref = change.after.ref.parent; 
  const now = Date.now();
  const cutoff = now - CUT_OFF_TIME;
  const oldItemsQuery = ref.orderByChild('lastUpdated').endAt(cutoff);
  const snapshot = await oldItemsQuery.once('value');
  const updates = {};

  ref = ref.parent.child('deckLocs')

  snapshot.forEach(child => {
    updates[child.key] = null;
  });

  return ref.update(updates);
});

这是我的数据库结构

"xxxx-9d272" {
 "decks" : {
    "randomID12345" : {
      "lastUpdated" : 1558460300472
    },
    "randomID67890" : {
      "lastUpdated" : 1558460300472
    }
 },
 "deckLocs" : {
    "randomID12345" : {},
    "randomID67890" :{}
 }
}

谢谢。

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

解决方案


问题是我试图将更新应用到另一个目录并且该行ref = ref.parent.child('deckLocs')导致问题。如果它消失了,它会按预期工作。


推荐阅读