How to read data from cloud firestore with firebase function and loop and push it to list

Viewed 44

I am trying to read data from firestore collection to get notification token and push it to a list and pass the list to SendtoDevice function to send push notification.

I am facing issue when using foreach function and push the data getting error "for each is not a valid function"


let tokenList = [];

const userNotificationTokenDocs = await db.collection("userToken").doc(userId).get()
.then(querySnapshot => {
querySnapshot.forEach((doc) => {
console.log(doc.data().Tokens);
tokenList.push(doc.data().Tokens);
});
return null;
});

**other option which i tried, with same error.**

userNotificationTokenDocs.forEach(function(docs){
   console.log(docs.data());
   if(docs.data() != null){
    tokenList.push(docs.data().Token);
   }
});

Please help me, I am stuck with this.

1 Answers

found some BASIC mistake in your coding.

  • const userNotificationTokenDocs will always null , because you return null. forEach is void function.
  • Using await and then is unecessery. choose 1.
  • => arrow is a shorthand for { return expr; } . if you only have 1 expresion, you can shorthand with arrow. but if you have morethan 1 expression, just use bracket {} . documentation
  • userNotificationTokenDocs.forEach(function(docs){ this will error since null value cant use forEach.

I think your IDE should give you alert there's an error in your code. but you choose to run it instead fixing the error.

but is ok, keep learning code. :)

Related