I went though the firebase docs for updating a value in realtime database using Cloud Functions for Firebase, but am not able to understand.
My database structure is
{
"user" : {
"-KdD1f0ecmVXHZ3H3abZ" : {
"email" : "[email protected]",
"first_name" : "John",
"last_name" : "Smith",
"isVerified" : false
},
"-KdG4iHEYjInv7ljBhgG" : {
"email" : "[email protected]",
"first_name" : "Max1",
"last_name" : "Rosse13131313l",
"isVerified" : false
},
"-KdGAZ8Ws6weXWo0essF" : {
"email" : "[email protected]",
"first_name" : "Max1",
"last_name" : "Rosse13131313l",
"isVerified" : false
}
}
I want to update the isVerified using database trigger cloud functions. I don't know how to update a database value using cloud functions (language : Node.JS)
I wrote a code to automatically update the value of the key 'isVerified' of a user, when the user is created by using database trigger onWrite. My code is
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.userVerification = functions.database.ref('/users/{pushId}')
.onWrite(event => {
// Grab the current value of what was written to the Realtime Database.
var eventSnapshot = event.data;
if (event.data.previous.exists()) {
return;
}
eventSnapshot.update({
"isVerified": true
});
});
but when i deploy the code, and add a user to the database, the cloud function log shows the below error
TypeError: eventSnapshot.child(...).update is not a function
at exports.userVerification.functions.database.ref.onWrite.event (/user_code/index.js:10:36)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:35:20
at process._tickDomainCallback (internal/process/next_tick.js:129:7)
You are trying to call update() on a DeltaSnapshot object. There is no such method on that type of object.
var eventSnapshot = event.data;
eventSnapshot.update({
"isVerified": true
});
event.data
is a DeltaSnapshot. If you want to change the data at the location of the change represented by this object. Use its ref
property to get a hold of a Reference object:
var ref = event.data.ref;
ref.update({
"isVerified": true
});
Also, if you are reading or writing the database in a function, you should always return a Promise that indicates when the change is complete:
return ref.update({
"isVerified": true
});
I would recommend taking Frank's advice from the comments and study the existing sample code and documentation to better understand how Cloud Functions works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With