【问题标题】:Firebase cloud functions: How to get the reference to the document with wildcard notation?Firebase 云功能:如何使用通配符获取对文档的引用?
【发布时间】:2020-05-07 13:27:40
【问题描述】:

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

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

  2. 判断是否在“public”字段中从真到假

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

有什么建议吗?谢谢!

【问题讨论】:

    标签: javascript node.js firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    doc中所述:

    对于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。当然,基于此值,您可以使用 admin.firestore().doc(`public_posts/${postid}`); 重建 DocumentReference,这将提供与 change.after.ref 相同的对象。

    【讨论】:

    • 这很好,但肯定还有一种方法可以使用通配符符号中的这个“postid”东西......?不然你为什么要给它起个名字...?
    • @KarolinaHagegård 当然,您可以使用context 对象,请参阅此SO answer
    • 啊啊啊啊,太好了! :) 我喜欢这样。
    • @KarolinaHagegård 你可能会赞成另一个答案;-)
    【解决方案2】:

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

    要获取更新后的文档,您可以:

    change.after.val()

    要删除文档,您会这样做:

    change.after.ref.remove()

    【讨论】:

    • 您尚未声明“更改”...我猜您已将您的回复命名为 onUpdate,但既然可以命名它任何名称,如果您明确说明就好了这样说的。 :)
    猜你喜欢
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 2020-07-26
    • 2019-10-17
    • 1970-01-01
    • 2019-12-03
    • 2019-08-08
    相关资源
    最近更新 更多