Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

315
Views
¿Cómo agregar una colección de documentos a un documento recién creado en firebase?

Creé una aplicación de mensajería usando reaccionar y base de fuego. Cuando un usuario crea un nuevo chat grupal, se crea un nuevo documento y una nueva identificación de chat (creada aleatoriamente por Firebase), con la fecha en que se creó el chat. Los participantes del chat grupal se agregan a una nueva colección de 'participantes' que luego se agrega al nuevo documento de chat. Aquí está mi código:

 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 funciona y se devuelve correctamente como se muestra en console.log. Sin embargo, cuando trato de hacer referencia a él en las siguientes declaraciones, no funciona y Firebase crea un documento completamente nuevo, en lugar de agregarlo al que quiero.

¡No estoy seguro de lo que estoy haciendo mal! Gracias.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

El código me parece bien. ¿Estás seguro de que no se está ejecutando de nuevo la misma función que está creando nuevos chats? Además, no está esperando esas promesas devueltas por set() . Intenta refactorizar esto:

 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) })

Además, si está agregando varios documentos una vez, intente usar Escrituras por lotes para que todos se agreguen o no si alguno de ellos falla.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!