【问题标题】:How to push new data into firebase realtime database using cloud functions?如何使用云功能将新数据推送到 Firebase 实时数据库?
【发布时间】:2019-09-20 08:34:25
【问题描述】:

每次调用该函数时,如何使用 Cloud 函数更改 Firebase 数据库中的实时数据?我有一个名为 Points 的数据单元,我想在每次部署函数时将 Points 的值更改为 1 到 10 之间的随机数。我对使用 firebase 真的很陌生,所以我不知道从哪里真正开始。我查看了提供的大部分文档,但没有一个有帮助。我尝试了几件事,但惨遭失败。请帮忙

谢谢你,

这是我尝试过的......

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

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

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

ref.update(number)

【问题讨论】:

  • 您说您希望在调用云函数时更改数据,但是您拥有的代码的第一行来自用于在数据更改时调用函数的示例 - 正是对面的。您应该从 reading the documentation 开始编写一个通过 HTTP 请求调用的函数。
  • 我想使用 Pubsub 而不是 HTTP
  • 在这种情况下,these docsthis tutorial 应该是一个可以查看的地方。

标签: javascript firebase firebase-realtime-database google-cloud-functions


【解决方案1】:

您将在documentation 中找到有关如何通过 Pub/Sub 触发云功能的所有详细信息。

您还将在官方 Cloud Functions 示例中找到一个非常简单的“Hello World”示例:https://github.com/firebase/functions-samples/tree/master/quickstarts/pubsub-helloworld

您的云函数将如下所示:

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 Promises”的 3 个视频:https://firebase.google.com/docs/functions/video-series/

还要注意,你不能简单地做ref.update(number);:你会得到一个错误(Error: Reference.update failed: First argument must be an object containing the children to replace.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 2023-04-08
    • 2020-05-15
    相关资源
    最近更新 更多