简体   繁体   English

如何检测firestore中文档内的字段删除?

[英]How to detect a field deletion inside a document in firestore?

Here's the code we can use to know if a document is added, modified or removed:以下是我们可以用来了解文档是否被添加、修改或删除的代码:

db.collection("cities")
        .whereEqualTo("state", "CA")
        .addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot snapshots,
                                @Nullable FirebaseFirestoreException e) {
                if (e != null) {
                    Log.w(TAG, "listen:error", e);
                    return;
                }

                for (DocumentChange dc : snapshots.getDocumentChanges()) {
                    switch (dc.getType()) {
                        case ADDED:
                            Log.d(TAG, "New city: " + dc.getDocument().getData());
                            break;
                        case MODIFIED:
                            Log.d(TAG, "Modified city: " + dc.getDocument().getData());
                            break;
                        case REMOVED:
                            Log.d(TAG, "Removed city: " + dc.getDocument().getData());
                            break;
                    }
                }

            }
        });

Is there a way for a client to know if another client deleted a field inside a document?有没有办法让客户知道另一个客户是否删除了文档中的字段

The Firestore SDK does not provide any direct way to detect this situation. Firestore SDK 不提供任何直接的方法来检测这种情况。 You will have to write code to compare the prior snapshot with the new snapshot to see if any fields were added, changed or removed.您必须编写代码来比较之前的快照和新的快照,以查看是否添加、更改或删除了任何字段。 Your solution will have to:您的解决方案必须:

  • Retain the QuerySnapshot from the last invocation of your listener and compare that to the current snapshot保留上次调用侦听器的 QuerySnapshot 并将其与当前快照进行比较
  • Iterate each new DocumentSnapshot contained in the QuerySnapshot, and find the matching prior DocumentSnapshot from the retained QuerySnapshot.迭代包含在 QuerySnapshot 中的每个新 DocumentSnapshot,并从保留的 QuerySnapshot 中找到匹配的先前 DocumentSnapshot。
  • Diff the Map<String, Object> from the data of both current and prior DocumentSnapshot to find the specific change从当前和先前 DocumentSnapshot 的数据中区分Map<String, Object>以查找特定更改

This is obviously a non-trivial amount of code, and will be highly dependent on the actual field data you want to compare.这显然是一个不平凡的代码量,并且将高度依赖于您要比较的实际字段数据。

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

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