如何使用云功能将新数据推送到Firebase实时数据库中? [英] How to push new data into firebase realtime database using cloud functions?
问题描述
每次调用该函数时,如何使用Cloud函数更改Firebase数据库中的实时数据?我有一个名为Points的数据单元,我想在每次部署函数时将Points的值更改为1到10之间的随机数.我真的是刚开始使用Firebase,所以我不知道从哪里开始.我看了提供的大多数文档,但没有一个提供帮助.我尝试了一些尝试,但失败了.请帮助
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
谢谢
这就是我尝试过的...
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.
您还将在官方的Cloud Functions示例中找到一个非常简单的"Hello World"示例:
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 });
});
请注意,我们返回由 update()
异步方法返回的Promise,以便向平台指示工作已完成.我建议您观看Firebase视频系列中有关"JavaScript承诺"的3个视频:https://firebase.google.com/docs/functions/video-series/
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/
还请注意,您不能简单地执行 ref.update(number);
:您将得到一个错误( Error:Reference.update failed:第一个参数必须是包含以下内容的对象:要替换的子项.
)
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.
)
这篇关于如何使用云功能将新数据推送到Firebase实时数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!