gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:19:15 24 4
gpt4 key购买 nike

我设置了一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com