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

134
Visualizações
Updating a single value in firebase Doc

first time using firebase, i'm creating a blog, when i create a post i'm creating it as:

  const postCollection = collection(database, "posts");

  const submitPost = async () => {
    await addDoc(postCollection, {
      title,
      body,
      comments: [],
      liked: false,
      user: { name: auth.currentUser.displayName, id: auth.currentUser.uid },
    });
  };

Below each post i have a comment section, but i'm a bit confused about adding the comments.

I tried this:

const addComment = async (id) => {
    const targetPost = doc(database, "posts", id);
    await setDoc(targetPost, { ...targetPost, comments: [comment] });
  };

But it didn't work. Thanks in advance

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

0

If a post already exists then you can use updateDoc() to update specific fields in that document instead of setDoc() that will overwrite the document if exists. Since 'comments' is an array, you can use arrayUnion() to push new comments to your posts as shown below:

import { doc, updateDoc, arrayUnion } from "firebase/firestore";

const addComment = async (id) => {
  const targetPost = doc(database, "posts", id);

  await updateDoc(targetPost, {
    comments: arrayUnion(comment)
  });
};

Do not that if you need to update a specific comment then you'll have to read the whole post document, update comments array manually and then write the whole comments array back:

import { doc, getDoc, updateDoc } from "firebase/firestore";

const addComment = async (id) => {
  const targetPost = doc(database, "posts", id);
  
  const snapshot = await getDoc(targetPost)

  await updateDoc(targetPost, {
    comments: [...snapshot.data().comments, comment]
  });
};

Also checkout: Is there any way to update a specific index from the array in Firestore

For deleting a specific comment, you can use arrayRemove() if you know the exact comment object.

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