通过自动覆盖数据来优化Firebase数据库

时间:2017-07-28 10:17:33

标签: firebase firebase-realtime-database

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

  • 帖子
    • 最新

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

如何将帖子限制为20,以便在用户写入帖子>时最新的最后的帖子会自动退出(被删除)吗?

1 个答案:

答案 0 :(得分:0)

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.

相关问题