2017-07-28 40 views
0

在我火力地堡的應用程序優化火力地堡數據庫我有以下結構:通過自動覆蓋數據

  • 帖子
    • 最新

所有用戶可寫信給的帖子>最新的。我想將條目限制爲20個帖子以節省數據庫中的空間。超過20的帖子是不必要的,因爲它們永遠不會顯示在主頁上。

如何將帖子限制爲20,以便當用戶寫入帖子>最近最後的帖子會自動刪除(被刪除)嗎?

+0

檢查我的答案https://stackoverflow.com/a/45348229/3222713 – Pipiks

回答

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.