在 Cloud Functions for Firebase 中将对象从一个节点复制到另一个节点
Copy object from one node to another in Cloud Functions for Firebase
我正在使用 Cloud Functions for Firebase,但我坚持执行看似非常基本的操作。
如果有人添加 post,他会写到 /posts/
。我希望 post 的一部分保存在另一个节点下,称为 public-posts
或 private-posts
,使用与初始 post 中使用的相同的密钥。
我的代码如下所示
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.
我做错了什么?
如果您想在数据库触发器中更改数据库,您要么必须使用 Admin SDK,要么使用事件中提供的引用找到对相关节点的引用。 (您不能使用 functions.database
查找引用 - 用于注册触发器)。
最简单的大概就是用event.data.ref
(doc)找到你要写的位置的引用:
const root = event.data.ref.root
const pubPost = root.child('public-posts')
我正在使用 Cloud Functions for Firebase,但我坚持执行看似非常基本的操作。
如果有人添加 post,他会写到 /posts/
。我希望 post 的一部分保存在另一个节点下,称为 public-posts
或 private-posts
,使用与初始 post 中使用的相同的密钥。
我的代码如下所示
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.
我做错了什么?
如果您想在数据库触发器中更改数据库,您要么必须使用 Admin SDK,要么使用事件中提供的引用找到对相关节点的引用。 (您不能使用 functions.database
查找引用 - 用于注册触发器)。
最简单的大概就是用event.data.ref
(doc)找到你要写的位置的引用:
const root = event.data.ref.root
const pubPost = root.child('public-posts')