firestore OnCreate not triggered when creation is done by a sub document or collection

前端 未结 1 1404

So I am building a chat app using flutter and firebase and I need to trigger a function whenever two new users starting chatting with each other for the first time (whenever one

相关标签:
1条回答
  • 2021-01-28 03:36

    It doesn't get triggered when that same document is created by the subcollection.

    This is the normal behavior.

    As a matter of fact, if you create a document directly under a messages collection with the full path rooms/{roomId}/messages/{messageWithRandomId}, no intermediate documents will be created (i.e. no roomId document).

    So, when you say:

    the room document gets created along with the sub-collection messages containing a single message document with a randomId

    , if you only created the message document with a randomId, there is actually no room document created and, consequently, the Cloud Function is not triggered.

    The Firebase console shows in italics the roomId room "document" as a kind of "container" (or "placeholder"), in order to "materialize" the hierarchy and to allow you to navigate to the messageWithRandomId message document, but the room document doesn't exist in the Firestore database.


    Let's take a more generic example: Imagine a doc1 document under the col1 collection

    col1/doc1/
    

    and another one subDoc1 under the subCol1 (sub-)collection

    col1/doc1/subCol1/subDoc1
    

    Actually, from a technical perspective, they are not at all relating to each other. They just share a part of their path but nothing else. One side effect of this is that if you delete a document, its sub-collection(s) still exist.


    This means that you should either:

    Create yourself the roomId document under the rooms collection

    OR

    trigger your Cloud Function with:

    export const testfunction = functions.firestore.document('rooms/{_someRoom}/messages/{_someMessage}').onCreate(async (snapshot,context) => {
      //.....   
    }
    
    0 讨论(0)
提交回复
热议问题