Reputation: 141
I'm trying to console.log a document from Firestore in a Firebase Cloud Function. Can someone help me with the code ?
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')
})
}
Upvotes: 3
Views: 1375
Reputation: 83181
The following should work:
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)
})
})
})
Note that by having
functions.database.ref(`/profiles/{profileId}`).onUpdate()
in your onUpdate
function:
1/ You are using the syntax for the Realtime Database and not for Firestore;
2/ You are setting an event handler in a Cloud Function that is already triggered through an event (being here a call to the HTTPS Cloud Function URL).
Within your HTTPS Cloud Function, you should simply use the Firestore get()
method in order to read from the database. No need to set another event handler or any listener: the "one time" database read/query done with get()
will be triggered each time the HTTPS Function is called.
You may watch this official video: https://www.youtube.com/watch?v=7IkUgCLr5oA.
Upvotes: 3