I'm trying to validate if I already have add a book of the same name AND grade (course) I'm not 100% sure if && works as AND in REACT but I think it does cause didn't got any complaints in the code anyways moving on to the issue:
const register = (e) => {
e.preventDefault();
const docRef = db.collection('libros').doc();
docRef.get().then((doc) => {
if (doc.id.descripcion == descripcion && doc.id.grado == grado)
{
window.alert("Book exist already")
}
else {
docRef.set({
materia: materia,
descripcion: descripcion,
editorial: editorial,
grado: grado,
precio: precio,
id: docRef.id
}).then((r) => {
window.alert("Book added")
})}
})
}
This is the snip code of where I'm having the issue my idea is to loop through all the documents I have in that collection I'm not sure if i'm writing it correctly (clearly not cause is not working).
The idea is that Documents have a field called Description and course (descripcion and grado) and I want to compare the documents first to check if they have the same description and course, like they can have the same description but not the same grade or the same grade but not the same description
(which I think I have that logic correctly) : doc.id.descripcion == descripcion && doc.id.grado == grado
But it doesn't seem to be even running through that code, any tips are welcome and from what I understand is suppose to loop and check every document.
Edit: Forgot to add how it looks in the firebase and the input
CodePudding user response:
This will never find any duplicates:
const docRef = db.collection('libros').doc();
docRef.get().then((doc) => {
if (doc.id.descripcion == descripcion && doc.id.grado == grado) {
window.alert("Book exist already")
}
...
The reason for this is that the first line creates a reference to the new doc. The next line then tries to load that doc, which will never give you any data.
The doc.id.descripcion
anddoc.id.grado
are also wrong, and should probably be doc.data().descripcion
anddoc.data().grado
. But that doesn't matter too much, since you'll never get a document from get()
anyway, since you're trying to load a document from a reference you just created and never wrote to.
To ensure something is unique in Firestore, use it as the ID of the documents. So if you want the book name and grade to be unique, create the document ID from the book name and grade, instead of asking Firestore to generate a unique ID for you:"
const docId = descripcion grado;
const docRef = db.collection('libros').doc(docId);
docRef.get().then((doc) => {
if (doc.exists) {
window.alert("Book exist already")
}
...