【问题标题】:Cloud Function for Firebase Type Error - Cannot Read PropertyFirebase 类型错误的云函数 - 无法读取属性
【发布时间】:2017-08-22 04:38:02
【问题描述】:

我正在尝试编写一个云函数,只要有人使用我们的旧版应用创建记录,它就会创建一个记录(我们已经更改了 Firebase 后端架构并希望慢慢迁移用户)。但是,我的日志中出现以下错误:

TypeError: Cannot read property 'update' of undefined
    at exports.makeNewComment.functions.database.ref.onWrite.event (/user_code/index.js:14:92)
    at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:35:20
    at process._tickDomainCallback (internal/process/next_tick.js:129:7)

这是有问题的脚本:

//required modules
var functions = require('firebase-functions');
const admin = require('firebase-admin');

// Listens for new comments added to /comments/ and adds it to /post-comments/

exports.makeNewComment = functions.database.ref('comments/{commentId}').onWrite(event => {
  // Grab the current value of what was written to the Realtime Database.
  const commentId = event.params.commentId;
  const comment = event.data.val();
  // You must return a Promise when performing asynchronous tasks inside a Functions such as
  // writing to the Firebase Realtime Database.
  //return event.data.ref.parent.child('post-comments').set(comment);
  return functions.database.ref('post-comments/' + comment['postID'] + '/' + commentId).update(comment).then(url => {
    return functions.database.ref('user-comments/' + comment['postedBy'] + '/' + commentId).update(comment);
  });
});

//initialize
admin.initializeApp(functions.config().firebase);

谢谢!

【问题讨论】:

    标签: javascript node.js firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    根据 Doug 的回答,您可以将 functions.database.ref 替换为 event.data.ref.root

    var functions = require('firebase-functions');
    const admin = require('firebase-admin');
    
    exports.makeNewComment = functions.database.ref('comments/{commentId}').onWrite(event => {
    
      const commentId = event.params.commentId;
      const comment = event.data.val();
    
      return event.data.ref.root.child('post-comments/' + comment['postID'] + '/' + commentId).update(comment).then(url => {
        return event.data.ref.root.child('user-comments/' + comment['postedBy'] + '/' + commentId).update(comment);
      });
    });
    
    admin.initializeApp(functions.config().firebase);
    

    【讨论】:

      【解决方案2】:

      您不能在函数中间使用functions.database.ref() 来获取数据库中某处的引用。这仅用于定义新的云函数。

      如果您想引用数据库中某处的引用,您可以使用event.data.refevent.data.adminRef 来获取事件触发位置的引用。然后,您可以使用它的 root 属性将新的引用重建到数据库中的其他位置。或者你可以使用你的admin 对象来构建一个新的参考。

      查看sample code 可能会有所帮助,以了解事情的运作方式。

      【讨论】:

        猜你喜欢
        • 2016-10-22
        • 2020-08-01
        • 2022-09-23
        • 1970-01-01
        • 2019-03-18
        • 1970-01-01
        • 2018-06-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多