Prince Singh
Prince Singh

Reputation: 155

How to delete the array elements at index in firestore in javascript

    var arr = [ "GKRLrcpSL2BmKx3BfvWj","fMwH404fweoFJJqyE5Nf" , "DTurwbw64CWw4WosUQtC" ] //
arr.forEach((element) => {
    console.log(element);
    db.collection("Check").doc(element).get().then((docs) => {
        var data = docs.data();
        var arr = data.fill;
        arr.forEach((item) => {
            if(item['check'] == 'a') {
                db.collection("Check").doc(element).update({
                    fill: firebase.firestore.FieldValue.arrayRemove('check')
                }).then((val)  => {console.log("Updated")})
            }
        });
    });
});

Firestore Screenshot

I have a collection Check which consist of an array fill and there are objects in the fill i want to match the data in the fill and delete the value that index in firestore

Upvotes: 0

Views: 2550

Answers (3)

anlijudavid
anlijudavid

Reputation: 539

My solution is based on specifying the item ID to remove, example:

 firebase
        .firestore()
        .collection('projects')    // Collection
        .doc(project.id)           // ID string
        .delete()                  // Promise

Upvotes: -3

l1b3rty
l1b3rty

Reputation: 3642

If that works for you, use a map instead of an array, putting dummy values if necessary. Then you can remove the field directly.

fill: {
  a: xxx,
  b: xxx,
  check: xxx
}

db.collection("Check").doc(element).update({
  fill.check: firebase.firestore.FieldValue.delete()
})

Upvotes: 2

Doug Stevenson
Doug Stevenson

Reputation: 317372

FieldValue.arrayRemove() only works with the complete value of the array item to remove. It won't work for removing items by index. In fact, Firestore doesn't offer any way to directly modify array items by index.

What you'll have to do instead is read the document, modify the "fill" array in memory as you see fit, then update the document with the new value back to the document.

Upvotes: 4

Related Questions