0

Is angularfire2 can update multiple items by using queries instaed of item.$key

For example If I have this database tree

 Project
 --- items
 ------- {{key}}
 ------------ name: item1
 ------------ quantity : 0
 ------- {{key}}
 ------------ name: item2
 ------------ quantity : 0
 ------- {{key}}
 ------------ name: item3
 ------------ quantity : 12

I want to update the value of quantity for each item that contain 0 quantity to 30 such as this new database tree.

 Project
 --- items
 ------- {{key}}
 ------------ name: item1
 ------------ quantity : 30
 ------- {{key}}
 ------------ name: item2
 ------------ quantity : 30
 ------- {{key}}
 ------------ name: item3
 ------------ quantity : 12

Is that possible by using foreach or any other ways in Ionic 2?

1 Answer 1

1

To update any of the quantity , you need the key of that particular item.

Say, the key of item1 in your example is '-KpZqM09AEDkhuIYAHSt' then in order to update the quantity of item1 you need the reference of

Project/items/-KpZqM09AEDkhuIYAHSt

So to update all those entry having quantity===0 to 30, you can do:

  • Fetch all items using once() method of firebase with ref('items')

  • iterate over the items using forEach and store the keys of all those items having quantity ===0 in an array. Use .key to get key of each item in items

    var keyArray = [];
    firebase.database().ref('items').once('value', data => {
        data.forEach(item => {
            if (item.val().qty === 0) {
                keyArray.push(item.key);
            }
        });
    });
    
  • Once you get the keys, iterate over that key-array and for every key call firebase update() method with ref('items/'+keyOfItem)

    keyArray.forEach(keyOfItem => {
    firebase.database().ref('item/' + keyOfItem).update({
                quantity: 30
            });
    }
    //here keyOfItem is key of item having qty===0
    

    Don't forget that once() returns a promise which should be resolved first to get the second code working otherwise you will get keyArray as empty.
    Hope you find this helpful.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.