Firebase的云功能 - 删除最老的孩子

时间:2017-07-27 10:00:26

标签: javascript node.js firebase firebase-realtime-database google-cloud-functions

我设置了一个onWrite云功能,可以在用户更新内容时进行监听。我试图删除年龄最大的孩子,如果超过3岁,我就在那里:

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.."
        }
      }
    }
  }
}

因此在上面的示例中,当文本值添加到“media”时,最旧的将被删除。

1 个答案:

答案 0 :(得分:1)

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.