'How to read data from field value in real time database in Cloud functions(Javascript)
I am trying to read "OrderedTime" or any other field from the below structure(Image) but i always get output as "undefined" , but when i use "Amount" field then i am getting output as "Total Amount : 10₹" , I am not sure what i am doing wrong here.
exports.addCfTimeTodeliverables = functions.database.ref('/root/{VendorId}/deliverables/{key}').onCreate((snap, context)=>{
const data = context.params.VendorId
var requestSnapshot = snap.val().PhoneNumber; // getting undefined for all the fields (Not working as expected)
var requestSnapshot = snap.val().Amount; // getting "Total Amount : 10₹" (Working as expected)
console.log("------->"+requestSnapshot);
})
Could anyone help me to resolve this issue?
Solution 1:[1]
Our function must always return something, so we can solve this error by adding
return true;
after the last line.
From this:
exports.addCfTimeTodeliverables = functions.database.ref('/root/{VendorId}/deliverables/{key}').onCreate((snap, context)=>{
const data = context.params.VendorId
var requestSnapshot = snap.val().PhoneNumber; // getting undefined for all the fields (Not working as expected)
var requestSnapshot = snap.val().Amount; // getting "Total Amount : 10?" (Working as expected)
console.log("------->"+requestSnapshot);
})
To this:
exports.addCfTimeTodeliverables = functions.database.ref('/root/{VendorId}/deliverables/{key}').onCreate((snap, context)=>{
const data = context.params.VendorId
var requestSnapshot = snap.val().PhoneNumber; // getting undefined for all the fields (Not working as expected)
var requestSnapshot = snap.val().Amount; // getting "Total Amount : 10?" (Working as expected)
console.log("------->"+requestSnapshot);
return true;
})
Solution 2:[2]
I created a sample database with the same structure as yours and I got the value for PhoneNumber. What I noticed is that after getting that value I got the data as follows:
-------> 1111111111
{"severity":"WARNING","message":"Function returned undefined, expected Promise or value"}
Which I suspect is the message you're getting but in any case the data in being retrieved and the other message is only a warning. Anyway, the code I used is as follows, give it a try:
exports.addCfTimeTodeliverables = functions.database
.ref('/root/{VendorId}/deliverables/{key}')
.onCreate((snap, context) => {
const data = context.params.VendorId;
var requestSnapshot = snap.val().PhoneNumber;
console.log("------->"+requestSnapshot);
return null;
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ferregina Pelona |
