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

325
Visualizações
How to add a collection of documents to a newly created document in firebase?

I have built a messaging app using react and firebase. When a user creates a new group chat, a new document a new chat id (made randomly by Firebase) is created, with the date that the chat was created. The participants of the group chat are added to a new 'participants' collection which is added to the new chat document afterwards. Here is my code:

   db.collection('chats').add({ //add generates new chat document and id
            created: firebase.firestore.FieldValue.serverTimestamp() // when new chat was created
        })
            .then((docRef) => { //docRef.id contains newly created chat Id
                console.log("docRef is" + docRef.id) // this works, and new chatId is created
                    db.collection("chats")
                    .doc(docRef.id) //this isn't working, firebase is creating a new document with new random id, instead of using the docRef.id created above which represents the new chat.
                    .collection("participants")
                    .doc(auth.currentUser.id)
                    .set(currentUser)
                   
                    db.collection("chats")
                    .doc(docRef.id) //not working
                    .collection("participants")
                    .doc(user.id)
                    .set(otherUser)

...

docRef.id works and is returned correctly as shown by the console.log. However, when I try to reference it in the following statements it doesn't work and Firebase creates a brand new document, instead of adding to the one I want.

Not sure what I'm doing wrong! Thanks.

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

0

The code looks fine to me. Are you sure the same function isn't running again which is creating new chats? Also you are not awaiting those promises returned by set(). Try refactoring to this:

db.collection('chats').add({
  created: firebase.firestore.FieldValue.serverTimestamp()
}).then(async (docRef) => {
  // async ^^

  const newChatId = docRef.id
  console.log("New chat ID:" + newChatId)

  const newChatRef = db.collection("chats").doc(docRef.id)

  await newChatRef.collection("participants").doc(auth.currentUser.id).set(currentUser)
  await newChatRef.collection("participants").doc(user.id).set(otherUser)
})

Addionally, if you are adding multiple documents once, try using Batched Writes so they all are either added or not if any one of them fails.

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