Firestore使用参考属性添加自定义对象

时间:2019-05-01 17:07:20

标签: java android firebase google-cloud-firestore

我一直在向Firestore添加POJO,这些POJO会自动将它们解释为数据库的JSON对象。但是,我想让我的一个POJO具有Firestore称为 reference 类型的东西。属性类型将是.git/HEAD而不是DocumentReference吗?

我正在使用Java进行Android项目。

这是Firebase文档中的自定义对象示例。

String

然后添加到数据库

public class City {

private String name;
    private String state;
    private String country;
    private boolean capital;
    private long population;
    private List<String> regions;

    public City() {}

    public City(String name, String state, String country, boolean capital, long population, List<String> regions) {
        // ...
    }

    public String getName() {
        return name;
    }

    public String getState() {
        return state;
    }

    public String getCountry() {
        return country;
    }

    public boolean isCapital() {
        return capital;
    }

    public long getPopulation() {
        return population;
    }

    public List<String> getRegions() {
        return regions;
    }

    }

1 个答案:

答案 0 :(得分:0)

我已经做了一些简单的测试,并弄清楚了。 直接添加到Firestore中的自定义对象的属性类型的确为DocumentReference

下面是一个示例,其中Group的创建者是数据库中用户的reference

//Class POJO that holds data
public class Group {
   private String name;
   private DocumentReference creator;

   public Group(){}

   public Group(String name, DocumentReference ref) {
       this.name = name;
       this.creator = ref;
   }

   public String getName() { return this.name; }
   public DocumentReference getCreator() { return this.creator; }

}

// Add to database
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DocumentReference ref = db.collection("users").document(uid);

Group newGroup = new Group("My Group", ref);

db.collection("groups").document().set(newGroup);