I'm very aware that when you create a document in firebase it does generate a random unique ID but I want to create my own based on 5 random numbers let id = Math.floor(Math.random() * (99999 1));
now my question is how do I check that number I'm generating is not already in the documents I have created? is there a way to check documents ID and then make it randomize another number ?
so far I'm doing it outside because I have no idea how to check that inside my doc.set
I want both my doc.id
and the inner value id
to be the same
Code for reference:
let id = Math.floor(Math.random() * (99999 1));
const docId = `${id}`;
const registrarPedido = (e) => {
e.preventDefault();
const docRef = db.collection('usuarios').doc(user.uid).collection('pedidos').doc(docId)
docRef.set({
nombre: nombre,
grado: grado,
total: totalPrice,
escuela: escuela,
metodoDePago: "ACH",
estadoDePago: "Pendiente",
fecha: formattedDate,
id: docId,
entrega: "Retirar en Sede"
}).then((r) => {
history.push("/Inicio");
})
}
CodePudding user response:
- If you want be sure that it doesnt already exists, you could make a query to the document ID to check if it exists. If not, you can use it.
something like:
admin.firestore().collection('usuarios').doc(nuevo_id).get.then(res=>{
if(!res.data().exists){
admin.firestore.collection('usuarios').doc(nuevo_id).set({ nombre: nombre,
grado: grado,
total: totalPrice,
escuela: escuela,
metodoDePago: "ACH",
estadoDePago: "Pendiente",
fecha: formattedDate,
id: docId,
entrega: "Retirar en Sede"
})
}
});
- If you plan to use a lot of documents and the probability of using the same ID is big enough, you could make a document with every taken ID and use to generate a new ID.
In this case, I wouldn't use a random ID to make it easier and faster to generate.