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

309
Visualizações
Firebase firestore is there a way to write data from an array into a document and then subcollections?

I'm new to firebase in general and am trying to write parts of an array into a document and its remaining data in a document in a subcollection. Here is what I've done:

let db = admin.firestore();    
db.collection("User")
          .doc(fields.user)
          .collection("Address")
          .doc(fields.address)
          .set({
            User: fields.user,
            Address: fields.address,
          })
          .then(
            db.collection("User")
              .doc(fields.user)
              .collection("Address")
              .doc(fields.address)
              .collection("Orders")
              .doc(fields.ID)
              .set({
                ID: fields.ID,
              });

My biggest question is if there is a better way to do this? Here its a small sample but for cases it can get very long. Thanks in advance for any help.

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

if you have all the data in the first time. you can create your object with subcollections and then set it in one request

var obj = {
        User: fields.user,
        Address: fields.address,
        Orders: {
          ID: fields.ID,
        }
}
db.collection("User").doc(fields.user).set(obj)
.then(() => {
    console.log("Document successfully written!");
})
.catch((error) => {
    console.error("Error writing document: ", error);
});
about 4 years ago · Santiago Gelvez Relatório

0

I often prefer constructing longer paths using string interpolation, which would lead to:

db.doc(`User/${fields.user}/Address/${fields.address}`)
  .set({
    User: fields.user,
    Address: fields.address,
  })
  .then(
    db.doc(`User/${fields.user}/Address/${fields.address}/Orders/${fields.ID}`)
      .set({
        ID: fields.ID,
      });

Aside from that, you probably want to do this in a batched write so that either both of the writes succeed, or neither of them does.

about 4 years ago · Santiago Gelvez 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