【问题标题】:how to update a value in firebase realtime database using Cloud Functions for Firebase如何使用 Cloud Functions for Firebase 更新 Firebase 实时数据库中的值
【发布时间】:2017-09-14 06:16:48
【问题描述】:

我查看了使用 Cloud Functions for Firebase 在实时数据库中更新值的 firebase 文档,但我无法理解。

我的数据库结构是

{   
 "user" : {
    "-KdD1f0ecmVXHZ3H3abZ" : {
      "email" : "ksdsd@sdsd.com",
      "first_name" : "John",
      "last_name" : "Smith",
      "isVerified" : false
    },
    "-KdG4iHEYjInv7ljBhgG" : {
      "email" : "superttest@sds213123d.com",
      "first_name" : "Max1",
      "last_name" : "Rosse13131313l",
      "isVerified" : false
    },
    "-KdGAZ8Ws6weXWo0essF" : {
      "email" : "superttest@sds213123d.com",
      "first_name" : "Max1",
      "last_name" : "Rosse13131313l",
      "isVerified" : false
    } 
}

我想使用数据库触发云函数更新 isVerified。我不知道如何使用云函数更新数据库值(语言:Node.JS)

我编写了一个代码,当使用数据库触发器 onWrite 创建用户时,自动更新用户的键 'isVerified' 的值。我的代码是

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
    });
});

但是当我部署代码并将用户添加到数据库时,云功能日志显示以下错误

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)

【问题讨论】:

  • Cloud Functions 文档有一个部分和一组示例。你具体卡在哪里了?
  • 我无法理解文档中给出的示例,我需要帮助来理解要学习的相同或其他示例代码。提前谢谢你。
  • 不太可能有人会想出比文档中更好的示例。与其要求那样,不如展示您已经尝试过的内容以及您遇到的问题。
  • 您好,我已经更新了帖子,详细说明了我尝试过的操作和遇到的错误。请解决它,我的错误,我应该先给出细节。请帮帮我。
  • @ThooyavanManivaasakar 我遇到了几乎相同的问题,我想在创建新用户时更新 Users/{UserID}/(this field) 中的一个字段。我尝试了这些解决方案,但对我没有任何效果。你愿意帮助我吗?

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


【解决方案1】:

您正在尝试对 DeltaSnapshot 对象调用 update()。这种类型的对象上没有这样的方法。

var eventSnapshot = event.data;
eventSnapshot.update({
    "isVerified": true
});

event.data 是一个DeltaSnapshot。如果要更改此对象表示的更改位置的数据。使用其ref 属性来获取引用对象:

var ref = event.data.ref;
ref.update({
    "isVerified": true
});

另外,如果您在函数中读取或写入数据库,您应该always return a Promise 指示更改何时完成:

return ref.update({
    "isVerified": true
});

我建议从 cmets 处听取 Frank 的建议并研究现有的 sample codedocumentation 以更好地了解 Cloud Functions 的工作原理。

【讨论】:

  • 谢谢 Doug,也谢谢你 Frank,也谢谢你
  • @ThooyavanManivaasakar 您能否分享您的最终功能作为答案?这个答案仍然有一些模棱两可,示例代码和文档有很多值得质疑的地方——因此你的问题是我的相同问题。
  • 嗨@mobibob,目前的答案似乎很清楚并帮助了我,所以请告诉我你的确切问题,以便我可以提供相应的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-04
  • 2019-10-03
  • 1970-01-01
  • 1970-01-01
  • 2017-08-30
  • 2017-11-12
  • 1970-01-01
相关资源
最近更新 更多