问题
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 of them sent the first message) so I can store that information somewhere to show it later to the users as chat history (people who've got in contact with).
So my data tree looks like this : 'rooms/{roomId}/messages/{messageWithRandomId}'
Logically whenever a user sends the first message to another user the room document gets created along with the sub-collection 'messages' containing a single message document with a randomId. `
I've set up an OnCreate listener on the room's collection and it gets triggered whenever I manually create a new document under 'rooms'.
But it doesn't get triggered when that same document is created by the subcollection.
So my Code looks like this :
export const testfunction = functions.firestore.document('rooms/{_someRoom}').onCreate(async (snapshot,context) => {
// the function Core
}
回答1:
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
roomdocument gets created along with the sub-collectionmessagescontaining a single message document with arandomId
, 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) => {
//.....
}
来源:https://stackoverflow.com/questions/56761254/firestore-oncreate-not-triggered-when-creation-is-done-by-a-sub-document-or-coll