简体   繁体   中英

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 Points into a random number between 1 and 10 every time the function is deployed. I am really new to using firebase so I wouldn't know where to really start. I have looked most of the documentation provided but none of them helped. I have tried a few things but failed miserably. Please help

Thank you,

This is what I tried...

exports.userVerification = functions.database.ref('Points')

var ref = database().ref('Points')

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

ref.update(number)

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. )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM