'How to delete a field in a collection with firebase-admin?

I have a collection like this into firebase realtime database:

enter image description here

I need to delete the first element (the one that finishes with Wt6J) from server side using firebase-admin.

I have this simple code:

const deleteNotification = () => {
  const key1 = 'FhN6Ntw8gyPLwJYVzcHy0E8Wq5z2';
  const key2 = '-MzGhZ2psGLivIfTWt6J';
  const notsRef = db.ref(`notifications/${key1}/${key2}`);
  notsRef.remove();
};

This doesn't work. What method should I use to delete a specific field? How do you think I can do it?



Solution 1:[1]

I would think to use await in a try catch block. Await starts another thread which returns once it has completed. As people said above - your cloud function is likely being killed before the remove actually happens.

const deleteNotification = async () => {
  try{
    const key1 = 'FhN6Ntw8gyPLwJYVzcHy0E8Wq5z2';
    const key2 = '-MzGhZ2psGLivIfTWt6J';
    const notsRef = db.ref(`notifications/${key1}/${key2}`);
    await notsRef.remove();
  } catch( err ) {
    console.log( 'failed to remove record.' );
    console.log( err );
  }
  console.log( 'removed record successfully.' );
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rushkeldon