2

I have been adding POJOs to Firestore that automatically interprets them as JSON objects for the database. However I want to have one of my POJOs have what Firestore calls a reference type. Would the attribute type just be DocumentReference instead of a String?

I'm working on an Android project using Java.

Here is the custom object example from the Firebase Docs.

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

    }

Then to add to the database


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

1 Answer 1

3

I've done some simple testing and figured it out. The attribute type is indeed DocumentReference for custom objects when adding directly to Firestore.

Here is an example where the creator of a Group is a reference to a user in the database:

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.