Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Firebase云函数:如何使用通配符符号获取对文档的引用?_Javascript_Node.js_Firebase_Google Cloud Firestore_Google Cloud Functions - Fatal编程技术网

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

Javascript Firebase云函数:如何使用通配符符号获取对文档的引用?,javascript,node.js,firebase,google-cloud-firestore,google-cloud-functions,Javascript,Node.js,Firebase,Google Cloud Firestore,Google Cloud Functions,以下是我尝试使用Firebase云函数所做的: 收听“public_posts”集合下其中一个文档中的更改 说明“公共”字段中的更改是否从“真”变为“假” 如果为true,则删除触发该函数的文档 对于步骤1和2,代码很简单,但我不知道步骤3的语法。获取触发函数的文档引用的方法是什么?也就是说,我想知道下面空行的代码是什么: exports.checkPrivate = functions.firestore .document('public_posts/{postid}').onUpdate(

以下是我尝试使用Firebase云函数所做的:

  • 收听“public_posts”集合下其中一个文档中的更改

  • 说明“公共”字段中的更改是否从“真”变为“假”

  • 如果为true,则删除触发该函数的文档

  • 对于步骤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
    参数具有before和before属性 在田野之后。每一个都是一个
    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;
         }
    });
    

    更新以下卡罗琳娜·哈格格的评论: 如果要获取
    postid
    通配符的值,需要使用
    context
    对象,如:
    context.params.postid


    严格来说,您得到的是文档id,而不是它的
    DocumentReference
    。当然,基于此值,您可以使用
    admin.firestore().doc(`public_posts/${postid}`)重建
    DocumentReference
    将给出与
    更改相同的对象。在.ref

    之后,onUpdate侦听器返回一个
    更改
    对象()

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

    change.after.val()

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


    change.after.ref.remove()

    这很好,但肯定还有一种方法可以使用通配符符号中的“posted”东西。。。?否则你为什么要给它起个名字@KarolinaHagegård当然,您可以使用
    上下文
    对象,请看这个。Aaaaaaah,很好!:)“我喜欢这个。”卡罗里纳赫德你可以投另一个答案的赞成票;-)你还没有宣布“改变”。。。我猜您已经在更新的
    onUpdate
    中命名了您的响应,但是由于可以命名任何东西,如果您明确地这样说就好了。:)