0

我想要编写创建每当有人使用我们的传统应用创建一个记录的记录云功能(我们已经改变了火力地堡后端架构并希望慢慢迁移用户)。不过,我发现了以下错误在我的日志:云功能的火力地堡类型错误 - 无法读取属性

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

谢谢!

回答

1

基于Doug的回答,您可以用event.data.ref.root取代functions.database.ref

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

不能使用functions.database.ref()在函数中获得裁判的地方在你的数据库。这仅用于定义新的云端功能。

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

这可能有助于了解一些sample code得到的东西是如何工作的感觉。

相关问题