简体   繁体   中英

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

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.

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; } { 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. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM