I have been trying to add new items to my "Cruceros" collection and I want to have the firestore document uid as the id of the item, but it is always empty and I dont know why this is happening and when the console.log shows "this.idCrucero" it shows what I want but it isnt in the firebase collection, this is my code:
import { inject, Injectable } from "@angular/core";
import { addDoc, collection, doc, Firestore, getDoc, getDocs, orderBy, query, setDoc } from "@angular/fire/firestore";
@Injectable({
providedIn: 'root',
})
export class CrucerosService {
private firestore = inject(Firestore);
public idCrucero: string = "";
async guardarCrucero(
idCrucero: any,
name: any,
subtitle: any,
imagenCrucero: any,
descripcion: any,
imagenDescripcion: any,
tituloQueHacer: any[],
imagenQueHacer: any[],
descripcionQueHacer: any[],
tituloCamarotes: any[],
descripcionCamarotes: any[],
imagenCamarotes: any[],
planos: any[],
lugares: any[],
precioLugares: any[],
puertos: any[]
) {
const obj ={
"idCrucero" : idCrucero,
"name" : name,
"subtitle" : subtitle,
"imagenCrucero" : imagenCrucero,
"descripcion" : descripcion,
"imagenDescripcion" : imagenDescripcion,
"tituloQueHacer" : tituloQueHacer,
"imagenQueHacer" : imagenQueHacer,
"descripcionQueHacer" : descripcionQueHacer,
"tituloCamarotes" : tituloCamarotes,
"descripcionCamarotes" : descripcionCamarotes,
"imagenCamarotes" : imagenCamarotes,
"planos" : planos,
"lugares": lugares,
"precioLugares": precioLugares,
"puertos": puertos
};
const Ref = collection(this.firestore, 'Cruceros');
const docRef = await addDoc(Ref, obj);
this.idCrucero = docRef.id;
console.log(this.idCrucero)
}
async obtenerCruceros(){
const Ref = collection(this.firestore, 'Cruceros');
const q = query(Ref, orderBy('name'));
const querySnapshot = await getDocs(q);
const cruceros = querySnapshot.docs.map(doc => ({ id:doc.id, ...doc.data()}));
return cruceros
}
async actualizarCrucero(id: string, formData: any) {
const cruceroRef = doc(this.firestore, 'Cruceros', id.toString());
await setDoc(cruceroRef, formData, { merge: true });
}
async obtenerCruceroPorId(id: string) {
const Ref = doc(this.firestore, 'Cruceros', id);
const docSnap = await getDoc(Ref);
if (docSnap.exists()) {
return docSnap.data();
} else {
console.log("No such document!");
return null;
}
}
}
addDoc
gives you a document ID only after the data you provided was successfully added. If you want the document ID to be added to the new document, you're going to have to generate the ID before writing the document with setDoc
instead of using addDoc
. (Either that, or update the document with the ID after you've created it.)
You can generate a random document ID without writing the document using doc()
with no path argument. Then you can use that to build the reference to the new document to create:
const id = doc(this.firestore).id;
const docRef = doc(this.firestore, 'Cruceros', id);
obj.idCrucero = id
await setDoc(docRef, obj);