When using the onUpdate function in Firebase, how do I retrieve the record that has been updated?
The first argument passed your onUpdate handler function is a Change object. This object has two properties, before
and after
, both DataSnapshot objects. These DataSnapshot objects describe the contents of the database before and after the change that triggered the function.
exports.foo = functions.database.ref('/location-of-interest')
.onUpdate((change) => {
const before = change.before // DataSnapshot before the change
const after = change.after // DataSnapshot after the change
})
per https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder#onUpdate
onUpdate(handler) => function(functions.Change containing non-null functions.database.DataSnapshot, optional non-null functions.EventContext)
So I'm guessing that you just need to pass a callback function into the onUpdate(callback)
trigger. Per the documentation, the record of that has been updated would seem to be passed in as the first argument. I would start by logging the arguments object inside the callback function.
The example inside the docs is:
// Listens for new messages added to /messages/:pushId/original and creates an
// uppercase version of the message to /messages/:pushId/uppercase
exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
.onCreate((snapshot, context) => {
// Grab the current value of what was written to the Realtime Database.
const original = snapshot.val();
console.log('Uppercasing', context.params.pushId, original);
const uppercase = original.toUpperCase();
// You must return a Promise when performing asynchronous tasks inside a Functions such as
// writing to the Firebase Realtime Database.
// Setting an "uppercase" sibling in the Realtime Database returns a Promise.
return snapshot.ref.parent.child('uppercase').set(uppercase);
});