0

I am trying to use the unique id that firebase gives to get the data value from the child. I can get the data value from the child by hardcoding the unique id. But the database will have multiples stored and I want to get newest stored data.

I have tried to use the pushId but it makes the child come back null

function handler(agent){ 
      const db = firebase.database();
 //  const numberParam = agent.parameters.checknumber;
      const ref = db.ref('/cnumber/transaction/{pushId}/');
       return ref.once('value')
      .then((datashot) =>{
          const number = datashot.child('cnumber').val();
          agent.add('The number is' + number);  
       console.log(number);
});
}

1 Answers1

0

If you're trying to retrieve the latest child node:

function handler(agent){ 
  const db = firebase.database();
  const ref = db.ref('/cnumber/transaction');
  return ref.orderByKey().limitToLast(1).once('child_added').then((datashot) =>{
      const number = datashot.child('cnumber').val();
      agent.add('The number is' + number);  
      return number;
  });
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks! My only question is how will this affect the chatbot if a new key is added with data? Will the chatbot stick to that current key or will if move to a new node? If so would it be better to add the session id of the chatbot some how? – user10741953 Dec 26 '18 at 14:24
  • Since the code in the answer uses `once('child_added')`, it will only read the latest child once when you call `handler`. If you want it to continue listening, you'll need to use `on()`. Check the Firebase documentation for the proper syntax in that case. – Frank van Puffelen Dec 26 '18 at 20:13