繁体   English   中英

Firebase 云函数:如何获取通配符文档的引用?

[英]Firebase cloud functions: How to get the reference to the document with wildcard notation?

以下是我试图用 Firebase 云函数做的事情:

  1. 收听“public_posts”集合下文档之一的变化。

  2. 判断更改是否在“公共”字段中从真到假

  3. 如果为真,删除触发 function 的文档

对于步骤 1 和 2,代码很简单,但我不知道步骤 3 的语法。获取触发 function 的文档参考的方法是什么? 也就是说,我想知道下面空行的代码是什么:

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

有什么建议吗? 谢谢!

文档中所述:

对于onWriteonUpdate事件, change参数具有 before 和 after 字段。 其中每一个都是一个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 object ,例如: context.params.postid

严格来说,您获得的是文档 ID,而不是其DocumentReference 当然,基于这个值,你可以用admin.firestore().doc(`public_posts/${postid}`);重建DocumentReference 这将给出与 change.after.ref 相同的change.after.ref

onUpdate 监听器返回一个Change object ( https://firebase.google.com/docs/reference/functions/cloud_functions_.change )

要获取更新的文档,您将执行以下操作:

change.after.val()

要删除文档,您将执行以下操作:

change.after.ref.remove()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM