【问题标题】:Firestore Add Custom Objects with Reference AttributeFirestore 添加具有引用属性的自定义对象
【发布时间】:2019-05-01 17:07:20
【问题描述】:

我一直在将 POJO 添加到 Firestore,它会自动将它们解释为数据库的 JSON 对象。但是,我想让我的 POJO 具有 Firestore 所称的 reference 类型。属性类型是否只是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);

【问题讨论】:

    标签: java android firebase google-cloud-firestore


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-01
      • 2020-05-17
      相关资源
      最近更新 更多