typescript - 無法從 Firestore 獲取文件
我正在嘗試在 Firebase Cloud Function 中使用 console.log 打印 Firestore 的一個文檔。有人可以幫我寫這段代碼嗎?
export const getUser = functions.https.onRequest((req, res) => {
const uid = req.query.uid
corsHandler(req, res, () => {
onUpdate(res, uid)
})
})
function onUpdate(res, uid) {
functions.database.ref(`/profiles/{profileId}`).onUpdate((change, context) => {
const profileId = uid
console.log('BEFORE: ', change.before.val())
res.send('OK')
})
}
答案#1
以下應該可行:
export const getUser = functions.https.onRequest((req, res) => {
const uid = req.query.uid
corsHandler(req, res, () => {
admin.firestore().collection('profiles').doc(uid).get()
.then(snapshot => {
console.log(snapshot.data())
res.send('OK')
})
.catch(err => {
console.error('ERROR:', err)
res.status(500).send(err)
})
})
})
請注意,透過擁有
functions.database.ref(`/profiles/{profileId}`).onUpdate()
在你的 onUpdate 函數中:
1/ 你正在使用 Realtime Database 的語法,而不是 Firestore 的語法;
2/ 您正在在已透過事件觸發的 Cloud Function 中設定事件處理程式(此處是對 HTTPS Cloud Function URL 的呼叫)。
在您的 HTTPS Cloud Function 中,您只需使用 Firestore 的 get() 方法即可從資料庫讀取資料。無需設定其他事件處理器或任何監聽器:使用 get() 完成的「一次性」資料庫讀取/查詢每次呼叫 HTTPS Function 時都會被觸發。
你可以觀看這個官方影片:https://www.youtube.com/watch?v=7IkUgCLr5oA。
