Skip to content Skip to sidebar Skip to footer

How To Push New Data Into Firebase Realtime Database Using Cloud Functions?

How can I use a Cloud function to change realtime data in my firebase database every-time the function is called? I have a data cell called Points and I want to change the value of

Solution 1:

You will find in the documentation all the details on how to trigger a Cloud Function via Pub/Sub.

You will also find a very simple "Hello World" example in the official Cloud Functions sample: https://github.com/firebase/functions-samples/tree/master/quickstarts/pubsub-helloworld

Your Cloud Function would then look like the following:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.randomNbr = functions.pubsub.topic('topic-name').onPublish((message) => {

      var ref = admin.database().ref();

      var number = Math.floor(Math.random() * (10)) + 1;

      return ref.update({ Points: number });

});

Note that we return the Promise returned by the update() asynchronous method, in order to indicate to the platform that the work is finished. I would suggest you watch the 3 videos about "JavaScript Promises" from the Firebase video series: https://firebase.google.com/docs/functions/video-series/

Note also that you cannot simply do ref.update(number);: you'll get an error (Error: Reference.update failed: First argument must be an object containing the children to replace.)


Post a Comment for "How To Push New Data Into Firebase Realtime Database Using Cloud Functions?"