![](/img/trans.png)
[英]Firebase Cloud Functions onCreate object undefined when creating a counter
[英]Firebase Cloud Functions: What to name parameters when using onCreate() method?
我正在編寫我的第一個雲 function。 有人能告訴我我寫的下面代碼中的{documentId}
參數是什么意思嗎? 它是否需要在其他地方匹配代碼,或者我可以在此處使用我想要的任何名稱來命名該文檔?
sendCommentReportEmail.js
import * as functions from 'firebase-functions'
export const sendCommentReportEmail = functions.firestore
.document('/commentFlags/{documentId}') // <-----what does `{documentId}` mean here and does it need to be verbatim with code elsewhere?
.onCreate((snapshot, context) => {
try {
// Get an object representing the document
// e.g. {'name': 'Marie', 'age': 66}
const newDoc = snapshot.data()
console.log('new doc: ', newDoc)
console.log('context example: ', context.timestamp)
} catch (error) {
console.error('error in function', error)
}
return null
})
commentFlags
集合中的示例數據:
commentId:
"rZCCJ1VchLJgyllHtZlo"
content:
"test comment again"
photoDocId:
"t3XS4bcfhZ38seCumpuC"
reportedBy:
"bkDhRIax0bMYjvSx2dazI3C2cIJ3"
violator:
"bkDhRIax0bMYjvSx2dazI3C2cIJ3"
如文檔中所述,這稱為通配符。 這意味着將為在commentFlags
集合中創建的任何文檔觸發 Cloud Function。
在 Cloud Function 中,您可以通過params
object 獲取此通配符的值,如下所示。 該值對應於觸發 Cloud Function 的 Firestore 文檔的 ID(即創建的文檔,因為您使用了onCreate()
觸發器)。
export const sendCommentReportEmail = functions.firestore
.document('/commentFlags/{documentId}')
.onCreate((snapshot, context) => {
const documentId = context.params.documentId;
// ...
return ...
})
我可以在這里使用我想要的任何名稱來命名該文檔嗎?
是的,您只需要在使用params
object 時使用相同的名稱,如上所示。 我知道的唯一限制是通配符不能包含正斜杠( /
)或一系列點,但我建議遵循與Firestore 文檔 ID 相同的限制。
請注意,路徑中可以有多個通配符,如下例所示:
exports.globalTriggerer = functions.firestore
.document('{colId}/{docId}')
.onCreate((snap, context) => {
console.log(context.params.colId);
console.log(context.params.docId);
return null;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.