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

148
Visualizações
Firestore cloud function add field to document

Im trying to write a cloud function that lets me create a collection with a document and than adds field to that document. currently my function creates the collection and comment but oreplaces each field every time and overwrites the existing one, so after all the data is pushed i only end up with one field. How do i go about adding a field each time? my code

if (data && typeof data === "object") {
   Object.keys(data).forEach((docKey) => {
  firestore
    .collection(collectionKey)
    .doc("quotes")
    .set(data[docKey])
    .then((res) => {
      console.log("Document successfully written!");
    })
    .catch((error) => {
      console.error("Error writing document: ", error);
    });
  //});
}

data

"2": {
    "Quote": "Lorem Ipsum"
  },
  "3": {
    "Quote": "123"
  },
  "4": {
    "Quote": "456"
  }

after i run the function the only thing that will be in the document quotes is the last entry "456". How do i go about all the fields staying?

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

0

It seems you are trying to update the doc but you are using the .set() function which updates your document with newly provided data. You will need .update() instead to keep your previous data.

if (data && typeof data === "object") {
   Object.keys(data).forEach((docKey) => {
  firestore
    .collection(collectionKey)
    .doc("quotes")
    .update(data[docKey])
    .then((res) => {
      console.log("Document successfully written!");
    })
    .catch((error) => {
      console.error("Error writing document: ", error);
    });
  //});
}
about 4 years ago · Juan Pablo Isaza Relatório

0

To add fields to an existing document, use update as Anuj's answer shows.

If you want to both create the initial document and update it with a single statement, you can pass the merge: true option to set():

firestore
  .collection(collectionKey)
  .doc("quotes")
  .set({ [docKey]: data[docKey] }, { merge: true })

You'll note I also added [docKey]: to the data, as I expect you want the value of docKey to become the field name.

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