[英]How to update value of a specific field in Firestore document?
How do I get its ID only Android Firebase Firestore and update a specific field only?如何仅获取其 ID Android Firebase Firestore 并仅更新特定字段?
I just want to update the 'consumption' value of electricity without updating all the data for one device.我只想更新电力的“消耗”值而不更新一台设备的所有数据。
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);
}
}
});
}
Each time you're calling .document()
without passing anything as an argument in the following reference:每次调用
.document()
而不传递任何内容作为以下参考中的参数时:
db.collection(currentUser)
.document() //👈
.update("deviceWat", hours);
It means that you're generating a brand new unique document ID.这意味着您正在生成一个全新的唯一文档 ID。 When you call
.update()
, you're trying to update a document that actually doesn't exist, since you only reserved a document ID and nothing more.当您调用
.update()
时,您正在尝试更新一个实际上不存在的文档,因为您只保留了一个文档 ID,仅此而已。
If you want to create a reference that points to a particular document inside the "currentUser" collection, then you have to pass the document ID of that document, which already exists in the database, and not generate a new one.如果要创建指向“currentUser”集合中特定文档的引用,则必须传递数据库中已存在的该文档的文档 ID,而不是生成新文档。 So to solve this, get the document ID of the item you want to update and pass it to the
.document()
function like this:因此,要解决此问题,请获取要更新的项目的文档 ID,并将其传递给
.document()
function,如下所示:
db.collection(currentUser)
.document("hnx81...803tY") //👈
.update("deviceWat", hours);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.