如何使用 Cloud Functions for Firebase 更新 Firebase 实时数据库中的值

2024-05-15

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

我的数据库结构是

{   
 "user" : {
    "-KdD1f0ecmVXHZ3H3abZ" : {
      "email" : "[email protected] /cdn-cgi/l/email-protection",
      "first_name" : "John",
      "last_name" : "Smith",
      "isVerified" : false
    },
    "-KdG4iHEYjInv7ljBhgG" : {
      "email" : "[email protected] /cdn-cgi/l/email-protection",
      "first_name" : "Max1",
      "last_name" : "Rosse13131313l",
      "isVerified" : false
    },
    "-KdGAZ8Ws6weXWo0essF" : {
      "email" : "[email protected] /cdn-cgi/l/email-protection",
      "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)

您正在尝试致电update()在 DeltaSnapshot 对象上。该类型的对象没有这样的方法。

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

event.data is a Delta快照 https://firebase.google.com/docs/reference/functions/functions.database.DeltaSnapshot。如果要更改此对象所代表的更改位置处的数据。使用其ref属性来获取引用对象:

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

另外,如果您在函数中读取或写入数据库,您应该总是返回一个 Promise https://firebase.google.com/docs/functions/terminate-functions指示更改何时完成:

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

我建议从评论中采纳弗兰克的建议并研究现有的示例代码 https://github.com/firebase/functions-samples/ and 文档 https://firebase.google.com/docs/functions/更好地了解 Cloud Functions 的工作原理。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Cloud Functions for Firebase 更新 Firebase 实时数据库中的值 的相关文章

随机推荐