Devasatyam
Devasatyam

Reputation: 665

Cloud Functions for Firebase: How to get the value of the data that was deleted

When I add a cloud function responding to a delete event, like this one:

exports.onDeleteSector = functions.database.ref('/sectores/{idSector}').onDelete((event) =>

I can get the key to the sector being deleted in event.params.idSector proving the trigger works, however, event.data.val() returns null.

The deleted record contains the references to the children to be deleted. How can I get those before the parent is gone?

Thanks

Upvotes: 6

Views: 1963

Answers (3)

wobsoriano
wobsoriano

Reputation: 13434

Current way of getting the deleted data from onDelete trigger is like this:

exports.userDeleted = functions.firestore
  .document("users/{userId}")
  .onDelete((snapshot) => {
    const original = snapshot.data();
    // original contains the deleted data
  });

Upvotes: 2

Devasatyam
Devasatyam

Reputation: 665

The value of the entry being deleted is available at:

event.data.previous.val()

Upvotes: 2

Doug Stevenson
Doug Stevenson

Reputation: 317467

event.data.val() returns null, because that's the current value of the database at the time of the trigger. For all kinds of database triggers, this is going to be the case. For onDelete, this will always be null.

If you want to see what was previously at that location, before the event happened, take a look at event.data.previous.val(). Also see the docs for DeltaSnapshot, which is the data type for event.data.

Upvotes: 10

Related Questions