Cloud Function for Firebase Typeerror - 无法读取 属性

Cloud Function for Firebase Type Error - Cannot Read Property

我正在尝试编写一个 Cloud Function,每当有人使用我们的遗留应用程序创建记录时,它都会创建一条记录(我们已经更改了 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);

谢谢!

您不能在函数中间使用 functions.database.ref() 来获取对数据库中某处的引用。那只是为了定义一个新的云函数。

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

查看一些内容 sample code 可能有助于了解事情的运作方式。

根据 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);