【问题标题】:Optimising Firebase database by automatically overwriting data通过自动覆盖数据优化 Firebase 数据库
【发布时间】:2017-07-28 10:17:33
【问题描述】:

在我的 Firebase 应用中,我具有以下结构:

  • 帖子
    • 最新

所有用户都可以写帖子 >最新。我想将条目限制为 20 个帖子以节省数据库中的空间。超过 20 条的帖子是不必要的,因为它们永远不会显示在主页上。

如何将帖子限制为 20 个,这样当用户写入 帖子 > 最新时,最后的帖子会自动下降(被删除)?

【问题讨论】:

标签: firebase firebase-realtime-database


【解决方案1】:

This sample should help you.

你需要这样的东西:

const MAX_LOG_COUNT = 20;

exports.removeOld = functions.database.ref('/Posts/Latest/{postId}').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.

【讨论】:

    猜你喜欢
    • 2019-04-28
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    相关资源
    最近更新 更多