简体   繁体   English

如何在Firebase Cloud Functions中删除包含嵌套子节点的子节点?

[英]How to delete a child node including nested child nodes in Firebase Cloud Functions?

I'm using Firebase Cloud Functions to delete a child node when the event is expired and all the values get removed except a nested child node it doesn't get removed 事件到期后,我正在使用Firebase Cloud Functions删除子节点,所有值都将被删除,但嵌套子节点不会被删除

what's the issue and how to fix it? 有什么问题以及如何解决?

exports.removeOldMessages = functions.https.onRequest((req, res) => {
    const messagesRef = admin.database().ref('events')
    messagesRef.once('value', (snapshot) => {
        snapshot.forEach((child) => {
            child.forEach((child) => {
                if (Number(child.val()['endDate']) <= new Date().getTime()) {
                   child.ref.set(null)
              }
            })
        })
    })
    return res.status(200).end()
})

here is the JSON 这是JSON

{   "events" : { "N5iTuYzAbJa02RauxCl3uh2Nggz1" : {  
"-LNmIvSdrwK96KCGcmXm" : {
    "addedBy" : "Riyadh Figures",
    "coordinate" : [ 24.70914690943994, 46.78851541131735 ],
    "endDate" : "1538442801.0",
    "imagePath" : "-LNmIvSdrwK96KCGcmXm",
    "key" : "-LNmIvSdrwK96KCGcmXm",
    "title" : "hjihgf",
    "userPicture" : "N5iTuYzAbJa02RauxCl3uh2Nggz1"   } }

I don't understand what you're trying to achieve, by far you want to delete the event node if it's expired. 我不明白您要达到的目的,到目前为止,如果事件节点已过期,您要删除它。 Try it like below 尝试如下

var deleteObj ={}
messagesRef.once('value', (snapshot) => {
    snapshot.forEach((childSnap) => {
        childSnap.forEach((innerChild) => {
            if (Number(innerChild.val()['endDate']) <= new Date().getTime()) {
      // you can do this in two ways
      // step 1: Direct Deleting
               admin.database().ref('/events/' + childSnap.key + '/' + innerChild.key).set({}); 
      // step 2: Pass into Object
              deleteObj['/events/' + childSnap.key + '/' + innerChild.key] = null;
     // As you asked for deleting coordinate
             deleteObj['/events/' + childSnap.key + '/' + innerChild.key +'/' + 'coordinate']  = [] or {}; // this will do
          }
        })
    })
})

   if(deleteObj) // Step 2 
       admin.database().ref().update(deleteObj).then(function(){
           // console.log("Deleted");
       })

Step 2 will be helpful if you have more than one nodes to delete as fb support multipath update or delete 如果您要删除多个节点,则步骤2将很有帮助,因为fb支持多路径更新或删除

Keep one thing, as Doug said in your question comment. 如Doug在您的问题评论中所说,请保留一件事。 Why you have download entire data to delete some nodes alone. 为什么要下载整个数据来单独删除某些节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM