繁体   English   中英

Firestore 将哈希图添加到 Firestore 中的地图字段

[英]Firestore adding hashmaps to a map field in Firestore

我正在尝试使用键-> 值对在我的 firestore 数据库中创建对象映射。 这个想法是在我的属性文档中拥有一张房间对象的地图,其中客厅将是键和值的对象。 喜欢下图

房间地图

房间地图

我迷失了将对象添加到 firestore 的正确方法,因为房间地图已经存在,所以我如何向其中添加键-> 值对? 我还需要在下面的代码中执行搜索,以便我可以获取属性文档并将对象添加到房间地图字段中

FirebaseFirestore db = FirebaseFirestore.getInstance();
final CollectionReference propertyRef = db.collection("Properties");

final Room room = new Room(roomName, feet, inches, imageUrl);

propertyRef.whereEqualTo("propertyId", propertyId).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
     if (task.isSuccessful()) {
          for (QueryDocumentSnapshot doc : Objects.requireNonNull(task.getResult())) {
              propertyRef.document(doc.getId())
     ----->   .update("rooms", ""+roomName+"", room);

              Log.d(TAG, "Firebase Success= " + imageUrl);
              Toast.makeText(CreatePropertyActivity3.this, "Property Created", Toast.LENGTH_LONG).show();
              exProperties();
              }
              } else {
                  Toast.makeText(CreatePropertyActivity3.this, "Error check log", Toast.LENGTH_LONG).show();
     }
   }
 });

db上使用document(String)方法,如果文档不存在,它将根据文档创建文档(https://firebase.google.com/docs/firestore/manage-data/add-data

Map<String, Object> room = new HashMap<>();
room.put("feet", "...");
...

db.collection("rooms").document("the new room id")
        .set(room)
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                  ...
            }
        })
        .addOnFalureListener(...)

这是如果您知道文档的 ID,或者想自己设置 ID。 如果是这样,您可以在添加新项目之前替换传递给.document(...)的参数。 或者,您可以使用add()方法,该方法将为您创建一个带有自动生成 ID 的新文档。

在您的情况下,似乎您正在设置自己的有意义的 ID(例如客厅、厨房),并且您应该在添加地图之前更改propertyId变量。 但是,这是多余的,因为您已经拥有描述房间的属性(即名称)。 所以使用add()并避免查询不存在的文档:

final HashMap<String, Object> newRoom = new HashMap<>();
newRoom.put(roomName, room);
...
propertyRef.add(newRoom)
    .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
        @Override
        public void onSuccess(DocumentReference documentReference) {
            Log.d(TAG, "DocumentSnapshot written with ID: " + documentReference.getId());
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.w(TAG, "Error adding document", e);
        }
    });

事实上,因为您使用whereEqualTo您总是获取对同一文档的引用并覆盖其内容。 只需使用add()功能并查看文档以获取更多示例。 希望有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM