Zac*_*low 3 java android firebase google-cloud-firestore
我使用 Cloud Firestore 的方式如下:
“事件”集合包含使用唯一事件 ID 作为名称的文档。这些文档中有许多“EventComment”对象 - 每个对象代表用户所做的评论。
要将“EventComment”对象添加到文档中,我使用以下命令:
EventComment mcomment = new EventComment();
mcomment.setComment("this is a comment");
Map<String, EventComment> eventMap = new HashMap<>();
eventMap.put(Long.toHexString(Double.doubleToLongBits(Math.random())), mcomment);
firestore.collection("events").document(event_id)
.set(eventMap, SetOptions.merge()).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Toast.makeText(EventCommentsActivity.this, "ya bastud", Toast.LENGTH_SHORT).show();
}
});
Run Code Online (Sandbox Code Playgroud)
我创建一个HashMapString 和我的对象“EventComment”,然后在文档中设置它。
但是,当我想检索给定文档中包含的所有“EventComment”对象时,我无法将其转换为 EventComment 对象,即我无法执行此操作:
DocumentReference docRef = db.collection("events").document("vvG17ZfcLFVna8");
docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
EventComment comment = documentSnapshot.toObject(EventComment.class);
}
});
Run Code Online (Sandbox Code Playgroud)
此外,尝试将 documentSnapshot 转换为 HashMap 会给出“未经检查的转换”消息,并最终失败。这个想法是使用注释来填充 RecyclerView。
我在想我可能需要重组存储数据的方式?
任何建议将不胜感激。
干杯
您猜对了,您需要重组存储数据的方式。我这么说是因为您在实际数据库中存储类型对象的方式EventComment不正确。正如您在有关配额和限制的官方文档中看到的,文档的最大大小为1MiB。1MiB所以如果你继续这样存储数据,你会在很短的时间内达到极限。
请记住,Cloud Firestore 针对存储大量小文档进行了优化。为了解决这个问题,我建议您更改数据库结构,如下所示:
Firestore-root
|
--- events (collection)
| |
| --- eventId (document)
| | |
| | --- //event details
| |
| --- eventId (document)
| |
| --- //event details
|
--- comments (collection)
|
--- eventId (document)
|
--- eventComments (collection)
|
--- eventCommentId (document)
| |
| --- //event comment details
|
--- eventCommentId (document)
|
--- //event comment details
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,每个类型的对象EventComment都作为单独的文档添加到events集合中。为了读取所有事件对象,请使用以下代码:
DocumentReference docRef = db.collection("events");
docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
EventComment comment = documentSnapshot.toObject(EventComment.class);
}
});
Run Code Online (Sandbox Code Playgroud)
编辑:
如果您想要给定 eventId 的列表commnets,请再次查看上面的数据库结构以了解如何表示它。正如您所看到的,我添加了一个名为的新集合comments,其中给定 eventId 中的每个新评论也存储为单独的文档。我想出了这个结构来避免嵌套地图。
如果您有兴趣,可以看一下我的一篇教程,其中我一步步解释了如何构建应用程序所需的数据库。
| 归档时间: |
|
| 查看次数: |
2500 次 |
| 最近记录: |