firestore添加带有参考属性的自定义对象



我一直在向firestore添加pojos,以自动将其解释为数据库的JSON对象。但是,我想让我的一个pojos具有Firestore所谓的参考类型。属性类型只是DocumentReference而不是String

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

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

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

然后添加到数据库


   City city = new City("Los Angeles", "CA", "USA",
       false, 5000000L, Arrays.asList("west_coast", "sorcal"));
   db.collection("cities").document("LA").set(city);

我已经进行了一些简单的测试并弄清楚了。直接添加到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);

最新更新