Removing item ref from Firebase Cloud Functions

I need to remove an item from the list, but the following code does not work:

exports.removeOldItems = functions.database.ref('/chat/usersOnline/{userId}')
    .onWrite(event => {
      const snap = event.data;
      if (!snap.exists()) return;

      snap.forEach(it => {                                                                                 
        if ( condition ) {
          it.ref.remove();   <---- THIS NOT WORK
        }
      })

    });

The statement "it.ref.remove()" runs but is not removing the children item. What could be wrong?

UPDATE

I do not know why, but using parent.once(...) solves the problem:

exports.removeOldItems = functions.database.ref('/chat/usersOnline/{userId}')
    .onWrite(event => {
      if (!event.data.exists()) return;
      const parentRef = event.data.ref.parent;

      return parentRef.once('value').then(users => {
        users.forEach(function(tabs) {                               
          tabs.forEach(instance => {                                  
            if ( condition ) {                                          
              instance.ref.remove();
            }
          })
        });
      });

    });

I used the following example as a guide: https://github.com/firebase/functions-samples/blob/master/limit-children/functions/index.js

Upvotes: 0

Views: 915

Answers (1)

Ramiz Ansari
Ramiz Ansari

Reputation: 524

this might be happening because your are not returning a promise. try something like that.

exports.removeOldItems = functions.database.ref('/chat/usersOnline/{userId}')
.onWrite(event => {
  const snap = event.data;
  var itemstoremove = [];
  if (!snap.exists()) return;

  snap.forEach(it => {                                                                                 
    if ( condition ) {
      itemstoremove.push(it.ref.remove());   <---- THIS NOT WORK
    }
  })
return Promise.all(itemstoremove);

});

Upvotes: 1

Related Questions