0

My goal is to update a specific document by adding +1 everytime is "buyed", This is how the data enters I can either use this:

const data = JSON.parse(window.localStorage.getItem("listaLibros"))

which comes like this in the console log:

enter image description here

or I can transform all that data into a single array (idk which way would be easier to achieve what I want to do which is why I mention both)

const allItems = [...data1, ...data2, ...data3]

and then it comes like this:

enter image description here

However the reason why I had them "separated" as 4,0,3 is because each array is from a DIFFERENT collection and this time I had none from the second collection which is why it brings 0.

Now the idea is that for every BOOK it adds a +1 as "ordered" in their respective collection each book has his own uid which in this case is added on the document as id one of the examples in the picture is PE-13620 for example.

how can I compare my array information which the collections I think the best approach would be using the one with the separate arrays that way I can divide it by collection

 let data1 = data[0] //Collection A let data2 = data[1] //Collection B let data3 = data[2] //Collection C 

I know you can use .where('id', 'array-contains', data[0].id) I think ? but how do I use this for updating each one matched ? and to add the +1 would it be as simple as doing something like this ?

.update({ ordered: ++1 }) 

Update 1 Image showing how the user select each piece of data from each collection before "paying"

enter image description here

Collection B is not always empty, but for this example it is.

Update 2

So when you are in the "pay" screen the 3 arrays from before merge into 1 (as I mention before... const allItems = [...data1, ...data2, ...data3])

enter image description here

and when the person is gonna press Pay I would need to know how to use the arrays data1, data2 and data3 to check into each book and update the collection and add a +1 in "ordered". So far I do a new document to store all this into an order but I haven't figure out how to update that the book has +1 in "ordered"

so for the order I do the following:

const docRef = db.collection('usuarios').doc(user.uid).collection('pedidos').doc(docId) docRef.get().then((doc) => { docRef.set({ acudiente: user.displayName, email: user.email, phone: phone, nombre: nombre, grado: grado, total: totalPrice, totalPagado: 0, escuela: escuela, metodoDePago: "ACH", banco: "Global Bank", estadoDePago: "Pendiente", fecha: formattedDate, id: docId, data: allItems }).then((r) => { history.push("/Inicio"); }) }) //I was thinking here add a query or something (for each one) but didn't //work it brings data1.id as undentified const librosRefNuevos = db.collection('libros'); const queryRefNuevos = librosRefNuevos.where('id', 'array-contains', data1.id); 

However if I do data1[0].id it does bring back the first id of the array so maybe a for each but idk how to do a for each with where... maybe I'm complicating myself that's why I'm here lol

I hope this was more descriptive let me know if require anything else

This is how it looks in the firebase

enter image description here

FIXED

 const ref1 = db.collection('libros'); const increment = firebase.firestore.FieldValue.increment(1); for (let i = 0; i < data1.length; i++){ ref1.doc(data1[i].id).update({ ordenado: increment }) } const ref2 = db.collection('libros_Opcionales'); for (let i = 0; i < data2.length; i++){ ref2.doc(data2[i].id).update({ ordenado: increment }) } const ref3 = db.collection('productos_AIB'); for (let i = 0; i < data3.length; i++){ ref3.doc(data3[i].id).update({ ordenado: increment }) } 
5
  • I highly recommend switching from a Book[][] to a Record<string, Book[]> where the string is the collection path or just the name. e.g. listaLibros = { "collectionA": booksInA, "collectionB": booksInB, "collectionC": booksInC }. Then if a particular collection is empty, you can simply omit it. Commented Oct 28, 2021 at 0:24
  • I think that piece of code got misunderstood data[0,1,2 etc] defines the collection 0 is the first one , 1 is the second collection , 2 is the third and last collection each bit has all the books from THAT collection which is why is showed as 4,0,3 in the array print Commented Oct 28, 2021 at 0:26
  • 2
    While I understand what you are trying to do I'll make myself clearer - if your code can be misunderstood, it's bad code. What if you needed to add a new collection? What if the order of the collection doesn't make sense? What if you needed to add a collection between A and B? What if a new person came along destructure your array into const [colA, colC] = data and obviously missed colB so now all the data is messed up? What if I only needed the data from C, how do I know that C is in index 2? How do I know which index is what 100 lines further down in the code? Commented Oct 28, 2021 at 0:36
  • Welp I said data is divided in 3 arrays each array represents a collection which I did mention. The way I divided is with data[0] as the first collection, data[1] as the second collection and lastly data[2] as the last collection. Commented Oct 28, 2021 at 0:43
  • Also I do not need new collections and the user can't add more than 3 because is getting the data from a table where you can select the books from each collection, I can upload a picture if you require it. Commented Oct 28, 2021 at 0:44

2 Answers 2

1
+50

I would simply iterate through each data array and check for the existence of a corresponding document in each collection before updating the field.

const data = JSON.parse(window.localStorage.getItem("listaLibros")); for (int i = 0; i < 3; i++) { for (const item of data[i]) { // Check libros const libro = await db.doc(`libros/{item.id}`).get(); if (libro.exists) { await db.doc(`libros/{item.id}`).update({ ordered: libro.get('ordered') + 1 }) } // Check libros_Opcionales const libroOpcional = await db.doc(`libros_Opcionales/{item.id}`).get(); if (libroOpcional.exists) { await db.doc(`libros_Opcionales/{item.id}`).update({ ordered: libroOpcional.get('ordered') + 1 }) } // Check productos_AIB const producto = await db.doc(`productos_AIB/{item.id}`).get(); if (producto.exists) { await db.doc(`productos_AIB/{item.id}`).update({ ordered: producto.get('ordered') + 1 }) } } } 
Sign up to request clarification or add additional context in comments.

5 Comments

Correct me if I'm wrong but wont the int 1=0; i < 3 would only do 3 documents ? the amount of documents in data1, data2 and data3 are always changing
Following this I think I would i < data1.lenght also for the db would be db.collection('libros').doc(data1[i].id) let me give it a few tries and i'll let you know
@ReactPotato My understanding was that data was made up of three arrays, each one of varying length. The second loop iterates through all the values, regardless of length. data only has three members, no?
yeah is only data1, data2 and data3 however I do not understand why you have for (int i = 0; i < 3; i++) wouldn't that just only check data 3 times ? Also I believe that you have to separate the for loops since they have different lengths. I'm gonna update what I just did based on what I saw from your code (Which is working) but the +1 seems to be overwriting instead of ++1
Also libro.get('ordered') doesn't work it just tells me is not defined so instead I decided to check for the value
0

Based on the other answer I manage to make an answer as well that works for me

const ref1 = db.collection('libros'); const increment = firebase.firestore.FieldValue.increment(1); for (let i = 0; i < data1.length; i++){ ref1.doc(data1[i].id).update({ ordenado: increment }) } const ref2 = db.collection('libros_Opcionales'); for (let i = 0; i < data2.length; i++){ ref2.doc(data2[i].id).update({ ordenado: increment }) } const ref3 = db.collection('productos_AIB'); for (let i = 0; i < data3.length; i++){ ref3.doc(data3[i].id).update({ ordenado: increment }) } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.