如何在 Firestore 中使用 POJO 更新所有文档中的一个字段? [英] How to update one field from all documents using POJO in Firestore?

查看:26
本文介绍了如何在 Firestore 中使用 POJO 更新所有文档中的一个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 Student POJO 类:

I have this Student POJO class:

public class Student {
    private String name, rollNumber;
    private boolean active;

    public Student() {
        //For Firebase
    }

    public Student(String name, String rollNumber, boolean active) {
        this.name = name;
        this.rollNumber = rollNumber;
        this.active = active;
    }

    public String getName() {
        return name;
    }

    public String getRollNumber() {
        return rollNumber;
    }

    public boolean isActive() {
        return active;
    }
}

这是我的数据库:

student-xxxxx
   -students
       -uid
         - name
         - rollNumber
         - active

有 100 名学生,有些是活跃的,有些则不是.我想让所有学生都不活跃.

There are 100 students, some are active and some are not. I want to make all students not active.

代码:

db.collection("students").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (DocumentSnapshot document : task.getResult()) {
                Student student = document.toObject(Student.class);
                // How to update???
            }
        }
    }
});

如何使用 POJO 将 active 更新为 false?谢谢!

How to update active to false using POJO? Thanks!

推荐答案

你可以用一种非常简单的方式来解决这个问题.除了 getter,您还应该为 active 属性创建一个 setter,如下所示:

You can solve this, in a very simple way. Beside the getter, you should also create a setter for your active property like this:

public void setActive(boolean active) {
    this.active = active;
}

一旦你创建了 setter,你就可以像这样直接在你的 student 对象上使用它:

Once you have created the setter, you can use it directly on your student object like this:

db.collection("students").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (DocumentSnapshot document : task.getResult()) {
                Student student = document.toObject(Student.class);
                student.setActive(false); //Use the setter
                String id = document.getId();
                db.collection("students").document(id).set(student); //Set student object
            }
        }
    }
});

此代码的结果是将所有学生对象的 active 属性更新为 false 并将更新后的对象设置为相应的引用.

The result of this code would be to update the active property of all you student objects to false and set the updated object right on the corresponding reference.

这篇关于如何在 Firestore 中使用 POJO 更新所有文档中的一个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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