javascript - Cloud Functions for Firebase - 删除最老的 child

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

我设置了一个 onWrite 云函数来监听用户更新内容的时间。如果有超过 3 个,我正在尝试删除最老的 child ,这是我在:

exports.removeOld = functions.database.ref('/users/{uid}/media').onWrite(event => {

    const uid = event.params.uid

    if(event.data.numChildren() > 3) {
        //Remove Oldest child...
    }

})

这些 child 中的每一个都有一个“timestamp”键。

{
  "users" : {
    "jKAWX7v9dSOsJtatyHHXPQ3MO193" : {
      "media" : {
        "-Kq2_NvqCXCg_ogVRvA" : {
          "date" : 1.501151203274347E9,
          "title" : "Something..."
        },
        "-Kq2_V3t_kws3vlAt6B" : {
          "date" : 1.501151232526373E9,
          "title" : "Hello World.."
        }
        "-Kq2_V3t_kws3B6B" : {
          "date" : 1.501151232526373E9,
          "title" : "Hello World.."
        }
      }
    }
  }
}

所以在上面的例子中,当文本值被添加到“media”时,最早的将被删除。

最佳答案

This sample should help you.

你需要这样的东西:

const MAX_LOG_COUNT = 3;

exports.removeOld = functions.database.ref('/users/{uid}/media/{mediaId}').onCreate(event => {
    const parentRef = event.data.ref.parent;

    return parentRef.once('value').then(snapshot => {
        if (snapshot.numChildren() >= MAX_LOG_COUNT) {
            let childCount = 0;

            const updates = {};

            snapshot.forEach(function(child) {
                if (++childCount <= snapshot.numChildren() - MAX_LOG_COUNT) {
                    updates[child.key] = null;
                }
            });

            // Update the parent. This effectively removes the extra children.
            return parentRef.update(updates);
        }
    });
});

You can find all Cloud Functions for Firebase samples here.

关于javascript - Cloud Functions for Firebase - 删除最老的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45347426/

相关文章:

node.js - nodejs Mongoose 错误 TS2551 : Property 'isDeleted' does not exist on type 'Document' . 你的意思是 '$isDeleted'

ios - iOS 上的 Firebase 实时 : Cannot access Realtime Database

node.js - 在 Firebase Functions 服务器中设置 Swagger Ui

javascript - 使用javascript正则表达式检测浮点输入

node.js - 如何更新 sencha cordova 版本

javascript - 如何使用 Javascript 在 Safari 中生成按键事件?

node.js - mongoose-paginate 按引用文档排序

firebase - flutter + Firebase | java.lang.IllegalStateException : FirebaseApp with name [DEFAULT] doesn't exist

javascript - JS Bootstrap 表将 bool 值显示为 YES 和 NO 而不是 1 和 0

javascript - 如何在 Express router Jest 测试中模拟方法?