Ramesh-X
Ramesh-X

Reputation: 5055

Saving custom datatypes in Firebase Firestore

I have this class structure that I need to store in Firebase Firestore.

class A {
 int i = 3;
}
class B {
 A xa = new A();
 A ya = new A();
}
class C {
 B b = new B();
 String name = "hi";
}

C c1 = new C();

I want to store the value c1 in a document.
One way of doing so is like this.

db.collection("Cs").document("c1").set({
  "b": {
    "xa": {
      "i": 3,
    },
    "ya": {
      "i": 3,
    },
  },
  "name": "hi",
});

And another way of doing it.

ref1 = db.collection("Cs").document("c1");
ref1.set({"name": "hi"});
ref2 = ref1.collection("B").document("b").collection("A");
ref2.document("xa").set({"i": 3});
ref2.document("xb").set({"i": 3});

Can anyone tell me what is the best way of doing this. If there is any other better way of doing this, can you please state that?

Upvotes: 0

Views: 477

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138834

There a huge difference between those two approaches. In the first one you add those objects beneath a single document while in the second you are using nested collections.

Can anyone tell me what is the best way of doing this.

Either the first approach nor the second is better to be used. I'm not sure what are you trying to achieve but in general you should design the database schema for the queries you want to perform.

Upvotes: 1

Related Questions