如何使用WriteBatch删除列表中的项目? [英] How to remove item in list with WriteBatch?

查看:45
本文介绍了如何使用WriteBatch删除列表中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Firebase Cloud数据库.我查询了一个收藏品,并得到了一份文件清单.每个文档都包含一个字段 cars ,其中包含字符串.如果数组包含至少三个字符串,我想从此数组(而不是整个数组)中删除字符串 carPath .否则,应删除整个文档.我正在使用WriteBatch.我做了什么:

I'm using Firebase Cloud database. I queried a collection and got a list of documents. Each document contains a field cars which contains strings. In case the array contains at least three strings I want to remove the string carPath from this array (not the whole array). Otherwise, it should remove the whole document. I'm using WriteBatch. What I did:

fireDB.document(groupPath).collection("users").whereArrayContains("cars",carPath).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful() && task.getResult() != null) {
            QuerySnapshot snapshot = task.getResult();
            for (DocumentSnapshot curr : snapshot.getDocuments()) {
                List<String> cars = (List<String>) curr.get("cars");
                if (cars == null) continue;
                if (cars.size() <= 2) {
                    batch.delete(snapshot.getReference());
                } else {
                    // What to do here?
                }
            }
        }
    }
});

如何使用WriteBatch删除列表中的一项?

How should I remove one item in the list with WriteBatch?

推荐答案

您要尝试做的只是 FieldValue.arrayRemove()进行定期更新一个>.除非您将使用

What you're trying to do is just a document update. You can do a regular update with FieldValue.arrayRemove(). Except you will do it in the context of a batch using update() instead of a standalone update.

batch.update(snapshot.getReference(), "cars", FieldValue.arrayRemove(carPath));

这篇关于如何使用WriteBatch删除列表中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆