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

175
Visualizações
I want to make sure the Post Is Not Liked multiple times by The same user using Firebase

I have these codes to make the Like functionality

/*Here I increment by 1 every time someone submit like*/ 
db.collection("post").doc(postId).update({
    likes: increment
})

/*Here I collect the uid of the user who submit Like and append to an Array*/
db.collection('post').doc(postId).update( {
      usersArray: firebase.firestore.FieldValue.arrayUnion( userId )
   });

now is possible to have code that runs every time someone submits Like to check if the user already exists in the usersArray?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Before updating the post document, you first need to read it in order to check if userId is already included in the usersArray array.

For that you shall use a Transaction to ensure that the document was not modified between the time you read it for checking the Array and the time you update it.

const postDocRef = db.collection('post').doc(postId);

return db
.runTransaction((transaction) => {
    // This code may get re-run multiple times if there are conflicts.
    return transaction.get(postDocRef).then((postDoc) => {
        if (!postDoc.exists) {
            throw 'Document does not exist!';
        }

        if (postDoc.data().usersArray.includes(userId)) {
            throw 'User has already liked this post!';
        }

        const newLikes = postDoc.data().likes + 1;
        transaction.update(postDocRef, {
            usersArray: firebase.firestore.FieldValue.arrayUnion(userId),
            likes: newLikes,
        });
    });
})
.then(() => {
    console.log('Transaction successfully committed!');
})
.catch((error) => {
    console.log('Transaction failed: ', error);
});

Keep in mind that even with this code, malicious users can still use your configuration data with their own code to write their UID into the array a second time. To prevent this, you'll want to write security rules to only allow adding the UID if it isn't in the array already (by comparing request.resource with resource).

about 4 years ago · Juan Pablo Isaza Relatório

0

Use cloud functions for counter increments like post likes.We can get updated and previous value of document in onUpdate function trigger on post collection,then we can check if user is already included in userArray and increment/decrement like count accordingly.

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