【问题标题】:Firestore DocumentReference SerializationFirestore 文档参考序列化
【发布时间】:2019-06-14 17:58:30
【问题描述】:

我有一个 pojo,它映射了一个 firestore 文档。该文档包含对其他集合的其他文档的引用。

class Game(var local: String? = null, var visitor: String? = null,
        var events: MutableList<DocumentReference> = mutableListOf(), var date: Date? = null): Serializable 

问题在于 DocumentReference 不可序列化。我读过我可以将路径保存为字符串,然后自己创建对象(FirebaseFirestore.getInstance().document(path)),但是在 firestore 中不再是 Reference 类型的字段。

所以我的问题是,这是好方法吗?另外,字段是字符串而不是引用有关系吗?

问候,迭戈

【问题讨论】:

    标签: android firebase kotlin google-cloud-firestore


    【解决方案1】:

    所以我的问题是,这是好方法吗?

    是的。 DocumenetReference 中最重要的部分是字符串路径。如果将其序列化,则可以重新构造 DocumentReference 对象,非常简单。

    作为结论,如果您需要序列化DocumentReference 对象,请使用DocumentReference 的getPath() 方法获取表示文档在数据库中的位置的文字字符串。要将路径字符串反序列化回DocumentReference 对象,只需使用FirebaseFirestore.getInstance().document(path)

    编辑:

    这意味着数据库中的字段现在是字符串而不是引用。

    没错。

    这有关系吗?我想作为参考一定有某种优势。

    是的,由于现在该属性是字符串类型,因此您无法再利用 DocumentReference 类提供的功能。但这是可以帮助您实现所需的解决方法。 String 类是可序列化的,而 DocumentReference 不是。

    【讨论】:

    • 这意味着数据库中的字段现在是字符串而不是引用。有关系吗?我想作为参考一定有某种优势。
    【解决方案2】:

    我有一个详细的答案here。代码是

    private ArrayList<String> docRefToString(ArrayList<DocumentReference> products) {
        ArrayList<String> newProducts = new ArrayList<String>();
        for (DocumentReference product : products) {
            newProducts.add(product.getPath());
        }
        return newProducts;
    }
    
    private ArrayList<DocumentReference> docStringToDoc(ArrayList<String> products) {
        ArrayList<DocumentReference> newProducts = new ArrayList<DocumentReference>();
        for (String product : products) {
            newProducts.add(FirebaseFirestore.getInstance().document(product));
        }
        return newProducts;
    }
    

    在 Parcel 实现中..

    private Request(Parcel in) {
        ...
        ArrayList<String> strProducts = in.createStringArrayList();
        this.products = docStringToDoc(strProducts);
        ...
    }
    
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        ...
        dest.writeStringList(docRefToString(this.products));
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-25
      • 1970-01-01
      • 1970-01-01
      • 2018-08-02
      • 1970-01-01
      • 2019-05-10
      • 2018-06-16
      • 2019-08-14
      相关资源
      最近更新 更多