【问题标题】:How can I increase the value of a Firestore subcollection-document-field?如何增加 Firestore 子集合文档字段的值?
【发布时间】:2020-03-17 19:07:22
【问题描述】:

所以,我正在开发一个 Android 应用程序,我尝试通过按一个按钮将字段的值增加 1。基本上,我有一组用户,每个用户都有一个帖子的子集合,每个帖子都有一个名为“申请人”的数字字段,我用它来计算有多少人申请了一份工作。

问题是我找不到查询确切文档字段的方法,因为我无法以编程方式获取文档 ID。我一直在尝试通过搜索其标题来识别该帖子,但没有运气。当我运行代码时,它不会抛出任何错误,应用程序不会崩溃,但我的数据库中仍然没有任何变化。

这是我的数据库结构:

public void executeTransaction(int position){
        db.runTransaction(new Transaction.Function<Void>() {
            @Nullable
            @Override
            public Void apply(@NonNull Transaction transaction) throws FirebaseFirestoreException {

                db.collectionGroup("posts").whereEqualTo("title", list.get(position).getTheTitle()).get()
                        .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                            @Override
                            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                                DocumentReference postRef = usersRef.document("posts");
                                DocumentSnapshot postSnapshot = null;
                                try {
                                    postSnapshot = transaction.get(postRef);
                                } catch (FirebaseFirestoreException e) {
                                    e.printStackTrace();
                                }
                                long newApplicants = postSnapshot.getLong("applicants") + 1;
                                transaction.update(postRef, "applicants", newApplicants);
                            }
                        });
                return null;
            }
        }).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Toast.makeText(context, "You have applied to this job!", Toast.LENGTH_SHORT).show();
            }
        });

这是在您点击“应用”按钮时运行的方法。参数“位置”只是帖子存储在本地ArrayList&lt;Post&gt; list 中的位置。

我怎样才能简单地增加帖子的applicants 值?

【问题讨论】:

  • 你能以编程方式获得userId吗?
  • @GauravMall 是的,我的 userId 和发帖者的 userId 也是
  • 为什么不能以编程方式获取帖子的ID?您组织它的方式应该能够为您提供职位。您能告诉我们如何保存帖子吗?
  • 我找不到任何方法来获取它的 ID。我有一个 ArrayList 列表,我保存从 Firestore 读取的帖子,这样:``` for (DocumentSnapshot documentSnapshot : documentSnapshots.getDocuments()) { Post post = new Post(); post.setTitle(documentSnapshot.getString("title")); post.setApplicants(documentSnapshot.getLong("applicants")); ... list.add(post); } notifyDataSetChanged(); ```
  • 现在检查我的答案,它应该可以工作。

标签: android firebase google-cloud-firestore


【解决方案1】:

执行此操作的正确方法是使用Transaction(单击此以转到文档)。基本上,文档中详细说明了它们的工作原理:

使用 Cloud Firestore 客户端库,您可以将多个操作分组到一个事务中。 当您想根据字段的当前值或其他字段的值更新字段的值时,事务非常有用。

您正在以正确的方式使用事务,但不是在最好的情况下。由于您只想更新一个价值交易,因此您的数据库可能会超负荷工作。一个简单的增量方法将使用FieldValue.increment() 完成工作:

DocumentReference postRef = db.collection("users").document(userId).collection("posts").document(postId);

// Atomically increment the population of the city by 50.
washingtonRef.update("applicants", FieldValue.increment(50));

您需要拥有要更新的帖子的 ID。

要解决您刚刚编辑 Post 类并添加以下内容的问题:

string id;

public void setId(string id) {
   this.id = id;
}

public string getId() {
   return id; 
}

当您收到帖子时,只需执行以下操作(也就是如何获取帖子 ID):

for (DocumentSnapshot documentSnapshot : documentSnapshots.getDocuments()) { 
    Post post = new Post(); 
    post.setId(documentSnapshot.getId());
    post.setTitle(documentSnapshot.getString("title")); 
    post.setApplicants(documentSnapshot.getLong("applicants")); ... list.add(post); 
} 
notifyDataSetChanged();

并且在更新applicants 字段时,要获取文档ID,只需执行以下操作:

string postId = post.getId();

然后继续您的正常代码。

【讨论】:

  • 您好!我也一直在尝试这种方式,但我遇到了同样的问题..我应该如何找到帖子 ID?这是这里的主要问题..
  • 对不起,伙计,但你就是不明白。我找不到任何可能的方法来获取帖子的 ID(文档的 ID)。
  • 我刚刚为您提供了获取帖子ID的方法
  • 我不想粗鲁什么的,但你显然不明白。您为我提供了一种获取帖子实例 id 的方法,但是要将帖子的 id 存储在 post 类的实例中,首先您必须从 firestore 获取自动生成的 id。就像我创建新帖子时一样,该 id 参数必须从文档名称中获取它的值。我发现用 @DocumentId 注释参数可能会解决这个问题。我会让你知道它是如何工作的。
  • 你可以确定!事实上,这是我第一次可见的“投票”。 Stack刚刚给我加了徽章。快乐的编码伙伴!
猜你喜欢
  • 1970-01-01
  • 2019-11-03
  • 1970-01-01
  • 2021-04-21
  • 2021-11-04
  • 1970-01-01
  • 2020-02-15
  • 2018-10-21
  • 2021-05-30
相关资源
最近更新 更多