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

不想你离开。 提交于 2021-01-20 12:48:44

问题


    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")})
            }
        });
    });
});

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


回答1:


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()
})



回答2:


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.




回答3:


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

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


来源:https://stackoverflow.com/questions/62276269/how-to-delete-the-array-elements-at-index-in-firestore-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!