B Best
B Best

Reputation: 1166

Firestore Add Custom Objects with Reference Attribute

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

Upvotes: 2

Views: 2200

Answers (1)

B Best
B Best

Reputation: 1166

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

Upvotes: 3

Related Questions