1

add array:

    const buy =  (e) => {
    const washingtonRef = firebase.firestore().collection("users").doc(props.uid)
    washingtonRef.update({
        orders: firebase.firestore.FieldValue.arrayUnion({ id: e.target.name, quantity: +1 })
    });
}

del array:

    const delPr = (e) => {
    const washingtonRef = firebase.firestore().collection("users").doc(props.uid)
    washingtonRef.update({
        orders: firebase.firestore.FieldValue.arrayRemove({ id: e.target.name, quantity: +1 })
    });
}

enter image description here

Is it possible to somehow change the quantity field?

  • "If you need to increment the value of an array member, you should get that array on the client, get the desired element, update it and then write the document back" See https://stackoverflow.com/a/60301382/3959488 – Marcelo Viana Feb 25 '21 at 17:56
  • So I have to completely rewrite the whole array of objects? – Yura Protsyk Feb 25 '21 at 22:17
  • Saving an object in JSON format will make it easier? – Yura Protsyk Feb 25 '21 at 22:47
  • Yes, if you use it as a map (like you said, a JSON object), then you can use the `increment` method. In the other hand you will no longer be able to use the `arrayUnion`and `arrayRemove` methods because they apply only to array, as the name says. – Marcelo Viana Feb 27 '21 at 08:25

1 Answers1

0

Update

You can use the increment method for map but you can't use it for an array, since it's not possible to call out an array element as a named field value.

And the other way to do it is to read the entire document, modify the data in memory and update the field back into the document, in nodejs sample:

function IncrementArray(myDoc) {
  let docData = _.cloneDeep(myDoc.data())
  docData.orders[0].quantity += 1
  docData.orders[1].quantity += 1
  return docData
}

firestore.collection('users').doc(doc.id).update(
  IncrementArray(doc)
)

References:

  1. https://stackoverflow.com/a/58310449/8753991
  2. https://stackoverflow.com/a/66366708/8753991
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
JM Gelilio
  • 3,482
  • 1
  • 11
  • 23