英文:
How to monitor if new document is created for specific user
问题
我应该如何将ID传递给上面的Cloud Functions代码,而ID是当前用户ID或用户名?
目前,认证是在应用程序中完成的,用户登录应用程序,但我不确定服务器上的Cloud Functions如何知道是哪个用户登录并与应用程序交互?
我只需要监视相关用户的“onCreate”事件。
英文:
Say we have the following code in Cloud Functions Typescript code:
functions.firestore.document("collectionName/"+ID).onCreate(...
How am I supposed to pass ID to Cloud Functions code above while ID is the current user ID or username?
Currently the authentication is done in the app and user enters the app, but I am not sure how Cloud Functions on the server can know who is this user who logged in and interacts with the app?
I need to monitor "onCreate" event only for the relevant user.
答案1
得分: 2
你不需要将任何内容“传递”给Firestore的onCreate
触发器。它只会在匹配的文档创建时运行,你需要指定要匹配的文档模式。当创建匹配的文档时,该函数会运行,并且你可以使用提供的context
来获取被创建的文档的ID。
我建议查看文档中的一个onCreate
触发器的示例:
exports.createUser = functions.firestore
.document('users/{userId}')
.onCreate((snap, context) => { ... }
在上面提供的示例中,触发器匹配了用户集合中的所有文档。userId
通配符包含了匹配的ID。你可以使用它来获取创建的文档的ID。使用通配符的文档,你可以从传递给函数的context
参数中获取ID。
以下是文档中使用onWrite
触发器的示例:
exports.useWildcard = functions.firestore
.document('users/{userId}')
.onWrite((change, context) => {
// 如果我们将`/users/marie`设置为{name: "Marie"},
// 那么context.params.userId == "marie"
// ... 并且 ...
// change.after.data() == {name: "Marie"}
});
英文:
You don't "pass" anything to a Firestore onCreate trigger. It just runs any time a matching document is created. You have to specify the pattern of the documents to match. When a matching document is created, the function runs, and you can use the provided context
to know the ID of the document that was created.
I suggest reviewing the documentation for an example of an onCreate trigger:
exports.createUser = functions.firestore
.document('users/{userId}')
.onCreate((snap, context) => { ... }
In the provided example above, the trigger matches all documents in the users collection. The userId
wildcard contains the ID that was matched. You can use that to know the ID of the document that was created. Using the documentation for wildcards you can get the ID from the context parameter passed to the function.
Here is the example from the documentation that uses an onWrite trigger:
exports.useWildcard = functions.firestore
.document('users/{userId}')
.onWrite((change, context) => {
// If we set `/users/marie` to {name: "Marie"} then
// context.params.userId == "marie"
// ... and ...
// change.after.data() == {name: "Marie"}
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论