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

B最佳:

我一直在向Firestore添加POJO,这些POJO自动将它们解释为数据库的JSON对象。但是我想让我的一个POJO具有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);

B最佳:

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

这是一个示例,其中a的创建者Groupreference数据库中用户的:

//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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章