Reputation: 942
My issue, cannot read the data from the write DB callback, check below for more details
I am using firestore with node.js cloud function, and I need to set DB listener to messages collection, below is the code of setting listener to the data and the data structure, and my issue that I cann please check the following data structure
Here is the second level and the added message
exports.sendNotificationDependsOnEvent = functions.firestore.document('events/{event}/messages/{message}')
.onCreate((snap, context) => {
const document = snap.val();
// I tried snap.val() and it's not worked
//and I tried snap.data (give me very long un related data)
//and I tried snap.data() and it throwing exception (data is not a function)
//and I tried snap.current.val (and no result for that)
const text = document.message;
console.log("Step 3 : get message text : " + text);
});
advise how can I read data from above data
Upvotes: 1
Views: 1652
Reputation: 83153
Your problem most probably comes from the fact that snap does not exist. You may have an error in the way you build the reference.
As detailed in the doc (https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document) it is recommended to check if the doc exist before trying to get its field values.
See this example (for node.js) from the doc referenced above:
var cityRef = db.collection('cities').doc('SF');
var getDoc = cityRef.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data());
}
})
.catch(err => {
console.log('Error getting document', err);
});
Can you check, in your code, if snap really exist, as follow?
exports.sendNotificationDependsOnEvent = functions.firestore.document('events/{event}/messages/{message}')
.onCreate((snap, context) => {
if (!snap.exists) {
console.log('No such document!');
} else {
console.log('Document data:', snap.data());
}
});
The console will log in the Functions Log.
Upvotes: 1