首页 > 解决方案 > Firebase 云功能:如何使用通配符获取对文档的引用?

问题描述

以下是我试图用 Firebase 云功能做的事情:

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

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

  3. 如果为真,则删除触发该函数的文档

对于第 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;
     }
});

有什么建议吗?谢谢!

标签: javascriptnode.jsfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


文档中所述:

对于onWriteonUpdate事件,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. 当然,基于此值,您可以重建DocumentReferenceadmin.firestore().doc(`public_posts/${postid}`);which 将给出与 相同的对象change.after.ref


推荐阅读