首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >云修复-文档命名问题

云修复-文档命名问题
EN

Stack Overflow用户
提问于 2021-11-20 21:16:02
回答 1查看 51关注 0票数 0

我很难实现正确的CloudFi还原文档命名。

我有一个有5000多张照片的网络存储服务器。照片名为1.jpg -> 5000.jpg。我决定为每一张照片添加一个评论系统。

这个应用程序将显示来自服务器的随机照片(例如。123.jpg)。用户将能够评论该照片,并回复其他评论。

目前唯一起作用的是像这样命名文档:»photo_1«->»photo_5000«,但建议不要使用:

不要使用单调增加的文档ID,例如:. Customer1、Customer2、Customer3、.这样的顺序ID可能会导致影响延迟的热点。

起作用的是:

  • 照片(收藏)
  • Photo_1 (文件)
  • Photo_comments (收藏)
  • UUID(文件)

// Android

代码语言:javascript
复制
int currentPhotoNumber = 13;
firebaseFirestore.collection("photos").whereEqualTo("photo_id", currentPhotoNumber).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {

        if (task.isSuccessful()) {
            QuerySnapshot snapshot = task.getResult();
            if (!snapshot.isEmpty()) {
                // Document with the photo_id of "currentPhotoNumber" already exists
            } else {

                // Document does not exist. We need to create one.
                Map<String, Object> data = new HashMap<>();
                data.put("photo_id", currentPhotoNumber);

                // Create a new document named photo_13
                firebaseFirestore.collection("photos").document("photo_" + currentPhotoNumber).set(data);
            }
        }

        // Add a comment to photo_13
        for (QueryDocumentSnapshot document : task.getResult()) {
            DocumentReference documentReference = document.getReference();
            documentReference.collection("photos").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {

                    Map<String, Object> data = new HashMap<>();
                    data.put("author", "Name");
                    data.put("author_id", "1234");
                    data.put("comment", "This is a comment for photo 13");
                    data.put("time", FieldValue.serverTimestamp());

                    documentReference.collection("photo_comments").add(data);
                }
            });
        }
    }
});

如果我用UUID创建文档并用photo_id设置字段“currentPhotoNumber”,那么它就会变得很麻烦,如果很多用户同时发布评论,如果photo_id没有设置为特定的照片,因为它会创建多个具有相同字段和值的文档(例如。photo_id = 13)。如何防止文档重复使用相同的字段值?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-21 10:40:32

对此,最简单的解决方案是使用CollectionReference#add()方法,其中:

使用指定的数据向此集合添加新文档,并自动为其分配文档ID。

也就是说,要标识一张照片,只需在名为imageName的文档中添加一个字段,该字段将保存实际的图像名称»photo_1« -> »photo_5000«

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70049920

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档