【问题标题】:Copy object from one node to another in Cloud Functions for Firebase在 Cloud Functions for Firebase 中将对象从一个节点复制到另一个节点
【发布时间】:2017-08-31 11:03:32
【问题描述】:

我正在使用 Cloud Functions for Firebase,但我被一个看似非常基本的操作所困扰。

如果有人添加帖子,他会写信至/posts/。我希望将该帖子的一部分保存在另一个名为public-postsprivate-posts 的节点下,使用与初始帖子中使用的密钥相同的密钥。

我的代码是这样的

const functions = require('firebase-functions');

exports.copyPost = functions.database
  .ref('/posts/{pushId}')
  .onWrite(event => {
    const post = event.data.val();
    const smallPost = (({ name, descr }) => ({ name, descr }))(post);
    if (post.isPublic) {
      return functions.database.ref('/public-posts/' + event.params.pushId)
        .set(smallPost);
    } else {
      return functions.database.ref('/private-posts/' + event.params.pushId)
        .set(smallPost);
    }
  })

我得到的错误信息是:functions.database.ref(...).set is not a function

我做错了什么?

【问题讨论】:

  • 我是不是在不应该的地方使用了复数函数?现在就来测试一下……
  • 哦,等一下,我需要调用database(),对吧?我猜“功能”应该仍然是“功能”?

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


【解决方案1】:

如果您想在数据库触发器中更改数据库,您必须使用 Admin SDK,或者使用您在事件中获得的参考来查找对相关节点的参考。 (您不能使用 functions.database 来查找引用 - 用于注册触发器)。

最简单的可能是使用event.data.ref (doc) 来查找要写入的位置的引用:

const root = event.data.ref.root
const pubPost = root.child('public-posts')

【讨论】:

  • 太棒了。非常感谢!
猜你喜欢
  • 2017-02-06
  • 1970-01-01
  • 2017-08-20
  • 1970-01-01
  • 2017-05-15
  • 1970-01-01
  • 1970-01-01
  • 2017-03-20
  • 2017-12-02
相关资源
最近更新 更多