Firebase toObject with ref

时间:2018-05-24 04:04:18

标签: android firebase google-cloud-firestore

使用云firestore,您可以使用document.toObject(YourClass.class);将文档转换为对象,其中类的变量与数据库中的变量匹配。但是,如果数据库中的某个变量是引用,那么您将在java类中使用哪种数据类型?请注意,我不仅要将其存储在我的数据模型中,还要检索它并使用表单的覆盖方法进行设置:

protected MyDataModel(Parcel in) {
    mString = in.readString();
}

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(mString);
}

如果我使用DocumentReference,那么在writeToParcel()中,我该如何编写它?另外,我如何在受保护的Parcel in构造函数中阅读它?我尝试了writeSerializable()readSerializable(),但DocumentReference未实现Serializable

3 个答案:

答案 0 :(得分:2)

我还没有使用过Java API,但我想你会想要使用DocumentReference类型。以下是firebase文档中的一些链接:
DocumentReference
CollectionReference
getDocumentReference

答案 1 :(得分:2)

如果需要序列化DocumentReference,请使用其getPath()方法来获取描述文档在数据库中位置的字符串。要将路径字符串反序列化回DocumentReference,请使用FirebaseFirestore.getInstance().document(path)

当您要进行这样的转换时,有时自己编写所有代码比使用Firestore SDK提供的内置对象序列化更为方便。

答案 2 :(得分:0)

我在document.toObject(YourClass.class);上遇到了同样的问题
我有一个Event类,该类包含id(文档ID)和对另一个集合subCategoryReference的引用。

我在Event上创建了简单转换器

例如:

val event = document
      .toObject(Event::class.java)
      .withId<Event>(document.id)
      .withReference<Event>((document.data["subCategoryReference"] as DocumentReference).path)

在您所猜测的Event类中,我有两个函数withIdwithReference 看起来像这样:

fun <T : Event?> withId(id: String): T {
  this.id = id
  return this as T
}

fun <T : Event?> withReference(reference: String): T {
  this.subCategoryRef = reference
  return this as T
}

您的类变量的名称必须与Firestore变量/字段的名称不同(只是您要在其上应用转换器的变量)-参见下图

在我的Firestore上,引用字段(变量)称为subCategoryReference,在Event类中,变量名称为subCategoryRef

让我知道你是否没有得到我。

希望对您有帮助...

Firestore控制台 Firestore console

Event Event Class

相关问题