【问题标题】:Update a specific value only How do I get the ID Firestore Android仅更新特定值 如何获取 ID Firestore Android
【发布时间】:2022-10-08 17:32:00
【问题描述】:

仅更新特定值我如何仅获取其 ID Android FireBase Firestore

我只想更新电力的消耗值而不更新一台设备的所有数据

public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    DeviceModel modal = deviceModelArrayList.get(position);

    holder.showName.setText(modal.getDeviceName());
    holder.showWat.setText(modal.getDeviceWat());
    holder.showUse.setText(modal.getDeviceUse());


    holder.addBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            hours = Integer.parseInt(String.valueOf(holder.showUse.getText()));
            if (hours < 24) {
                holder.showUse.setText(String.valueOf(++hours));
                db.collection(currentUser)
                        .document()
                        .update("deviceWat", hours);
            }
        }
    });
}

【问题讨论】:

    标签: android firebase google-cloud-firestore


    【解决方案1】:

    每次调用 .document() 时,在以下参考中没有将任何内容作为参数传递:

    db.collection(currentUser)
       .document() //?
       .update("deviceWat", hours);
    

    这意味着您正在生成一个全新的唯一文档 ID。当您调用update() 时,您正在尝试更新一个实际上不存在的文档,因为您只保留了一个文档 ID,仅此而已。

    如果要创建指向“currentUser”集合内的特定文档的引用,则必须传递该文档的文档 ID,该文档已存在于数据库中,而不是生成新文档。因此,要解决这个问题,请获取要更新的项目的文档 ID,并将其传递给 .document() 函数,如下所示:

    db.collection(currentUser)
       .document("hnx81...803tY") //?
       .update("deviceWat", hours);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 2021-11-20
      • 1970-01-01
      相关资源
      最近更新 更多