1

我有一个onWrite云端函数,用于侦听用户何时更新内容。我试图删除最早的孩子,如果有3个以上的,这是有我在我:Firebase的云端功能 - 移除最大的子女

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

    const uid = event.params.uid 

    if(event.data.numChildren() > 3) { 
     //Remove Oldest 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.." 
     } 
     } 
    } 
    } 
} 

所以在上面的例子中,当文本值被添加到“媒体”时,最旧的是删除。

+0

您可以添加火力孩子的结构? –

+0

当然,我已经更新了我的问题。 –

回答

0

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.