-2

I am trying to call the .forEach function in my Cloud functions and it even works, but it does not return what I need, I am trying to get the branch key and it just returns TRUE.

I cannot remove return from the second line (I think this is a mistake), because as soon as I remove it, an error appears.

return admin.database().ref('test/100').once('value').then(function(snapshot) {
  return snapshot.forEach(function(childSnapshot) {
     var childKey = childSnapshot.key;
     return childKey;
  });
}).catch(function(error) {
  return 'error';
})

My databse:

"test" : {
  "100" : {
    "ineedthis" : {
      "example" : "example"
    },
  },
}

Return:

True

I will be very grateful to everyone who helps.

2 Answers2

1

It looks like you're trying to use .forEach on an object. That will not work. It looks like you can just return snapshot.key directly:

return admin.database().ref('test/100').once('value').then(function(snapshot) {
  return snapshot.key)); // or snapshot.ineedthis
}).catch(function(error) {
  return 'error';
})
mwilson
  • 12,295
  • 7
  • 55
  • 95
0

According to the docs, snapshot.forEach returns a boolean, so it doesn't work like your typical js array iterator (which returns undefined).

What error is forcing you to return on the second line? And can you fix it by returning null after the iterator like this?

return admin.database().ref('test/100').once('value').then(function(snapshot) {
     snapshot.forEach(function(childSnapshot) {
         var childKey = childSnapshot.key;
         return childKey;
      });
      return null;
}).catch(function(error) {
  return 'error';
})

I wish I could comment, because mwilson is incorrect. The forEach function exists on the DataSnapshot object in this case. Hopefully you see this before marking that answer as correct.

rmccreary
  • 76
  • 6