Home > database >  how can i update a specific object property within an array in firebase
how can i update a specific object property within an array in firebase

Time:02-11

im having trouble updating the quantity property in my angular-firebase project

chosenMeal(meal,price,quantity){
  for (let i = 0; i < this.order.length; i  ) {
        const element = this.order[i];
        if(element.meal != meal){
          this.db.collection('tables').doc(this.table.propertyId).update({order:({meal,price,quantity})})
        }else{
        // my question
  }
}

so the logic is like this if the chosen meal isn't in the order array then add it to the order array in firebase, else if the meal exists on the order array just increment the quantity, i don't know how to update just the quantity in the order object in firebase, or i don't know how to access only the one property in a firebase object

enter image description here

CodePudding user response:

Update the array locally and after that update it in your database.

chosenMeal(meal,price,quantity){
  for (let i = 0; i < this.order.length; i  ) {
        const element = this.order[i];
        if(element.meal != meal){
          this.db.collection('tables').doc(this.table.propertyId).update({order:({meal,price,quantity})})
        } else {
           this.order[i].quantity  = 1;
           this.db.collection('tables').doc(this.table.propertyId).update({order: this.order})
        }
}

If you want to add/remove elements from the array you can use arrayUnion() or arrayRemove() https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array

CodePudding user response:

Unfortunately you can't update a single property of an object within an array. You can't even update a single index of an array for that matter. You need to get the entire array, modify it, then put it back. There are the arrayUnion() and arrayRemove() but those are for inserting and removing unique values.

You could use a firestore sub-collection rather than an array, so each order would be a document. You could then use the increment function: https://firebase.google.com/docs/firestore/manage-data/add-data#increment_a_numeric_value

  • Related