javascript - Firebase 云功能:如何使用通配符获取对文档的引用?
问题描述
以下是我试图用 Firebase 云功能做的事情:
收听“public_posts”集合下文档之一的变化。
判断更改是否在“公共”字段中从真到假
如果为真,则删除触发该函数的文档
对于第 1 步和第 2 步,代码很简单,但我不知道第 3 步的语法。获取触发该函数的文档的引用的方法是什么?也就是说,我想知道下面空行的代码是什么:
exports.checkPrivate = functions.firestore
.document('public_posts/{postid}').onUpdate((change,context)=>{
const data=change.after.data();
if (data.public===false){
//get the reference of the trigger document and delete it
}
else {
return null;
}
});
有什么建议吗?谢谢!
解决方案
如文档中所述:
对于
onWrite
和onUpdate
事件,change
参数有前后字段。这些中的每一个都是一个DataSnapshot
.
因此,您可以执行以下操作:
exports.checkPrivate = functions.firestore
.document('public_posts/{postid}').onUpdate((change, context)=>{
const data=change.after.data();
if (!data.public) { //Note the additional change here
const docRef = change.after.ref;
return docRef.delete();
}
else {
return null;
}
});
更新下面的 Karolina Hagegård 评论:
如果要获取postid
通配符的值,则需要使用如下context
对象:context.params.postid
.
严格来说,你得到的是文档 id,而不是它的DocumentReference
. 当然,基于此值,您可以重建DocumentReference
与admin.firestore().doc(`public_posts/${postid}`);
which 将给出与 相同的对象change.after.ref
。
推荐阅读
- python - 如何使用 Python 连接到 LDAP 服务器(版本 3.8.8)
- python - 使用python API从烂番茄中收集数据
- google-cloud-platform - GCP Vertex AI 中的批量预测
- javascript - vue - 数据引用另一个数据
- docker-compose - 如何查找 Cassandra 启动失败的原因
- c - 用一个例子解释重新养育
- python - Django Token 对象更新错误:django.db.utils.IntegrityError: UNIQUE constraint failed: authtoken_token.user_id
- openmodelica - 如何限制modelica中的解决方案域
- flutter - Flutter中常用导航功能如何编写单元测试用例
- python - 如何同时允许 matplotlib 事件处理和命令行输入?