Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

236
Visualizações
Retrieve an array from a Firestore document and store it to Node.Js then use it as tokens to send notifications

I've been trying to figure this out for hours and I just can't. I'm still a beginner with Node.js and Firebase. I need your help to be able to retrieve the tokens array in my "userdata" collection to Node.js and be able to use it to send notifications in the Cloud Function. So far this is what I've been working on. Here is what my database looks like: enter image description here

The receiverId is gathered from when I have an onCreate function whenever a user sends a new message. Then I used it to access the userdata of a specific user which uses the receiverId as their uid.

In the cloud function, I was able to start the function and retrieve the receiverId and print the userToken[key]. However, when I try to push the token it doesnt go through and it results in an error that says that the token is empty. See the image: enter image description here enter image description here

Your help would mean a lot. Thank you!

newData = snapshot.data();
       console.log("Retrieving Receiver Id");
       console.log(newData.receiverId); //uid of the user
        const tokens = [];
        const docRef = db.collection('userdata').doc(newData.receiverId);
                docRef.get().then((doc) => {
                     if (doc.exists) {
                         console.log("DocRef exist");
                         const userToken = doc.data().tokens;
                         for(var key in userToken){
                            console.log(userToken[key]);
                            tokens.push(userToken[key]);
                         }
                     } else {
                         // doc.data() will be undefined in this case
                         console.log("No such document!");
                     }
                 }).catch((error) => {
                     console.log("Error getting document:", error);
                 });
    
       //Notification Payload
      var payload = {
      notification: {
        title: newData.sendBy,
        body: 'Sent you a message',
        sound: 'default',
        },
        data: {
        click_action : 'FLUTTER_NOTIFICATION_CLICK',
        route: '/telconsultinbox',
        }
      };
    
    
      console.log("Sending Notification now.");
      console.log(tokens);
    
      try{
      //send to device
      const response = await admin.messaging().sendToDevice(tokens, payload);
      console.log('Notification sent successfully');
      console.log(newData.sendBy);
    
    
      }catch(err){
      console.log(err);
    
      }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think you should avoid using for..in to iterate through an array (you can read more about it in this answer). Try one of these 2 options:

  1. You could use forEach(), which is more elegant:
  userToken.forEach((token) => {
    console.log(token);
    tokens.push(token);
  });
  1. for-of statement:
  for(const token of userToken){
    console.log(token);
    tokens.push(token);
  }

Also, I would consider renaming userToken to userTokens, since it should contain multiple values. Makes the code a bit more readable.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda