Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

147
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda