Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my Cloud Firestore Transaction not merging when using SetOptions.merge()?

Just started with Firestore and use the SetOptions.merge() in a Cloud Firestore Transaction like this nothing special I guess:

final Map<String, Object> visitorMap = new HashMap<>();
visitorMap.put(Visitor.NOTIFY_ON_CHAT_MESSAGE, true);
visitorMap.put(Visitor.TIME, FieldValue.serverTimestamp());
final DocumentReference docRefVisitor = mFirestore
        .collection(VISITORS)
        .document(theId)
        .collection(VISITORS_USER)
        .document(getCurrentUser().getUserId());
mFirestore.runTransaction(new com.google.firebase.firestore.Transaction.Function<void>() {
    @Nullable
    @Override
    public void apply(@NonNull Transaction transaction) throws FirebaseFirestoreException {
        transaction.set(docRefVisitor, visitorMap, SetOptions.merge());
    }
})

The docs say:

If the document does not exist, it will be created. If the document does exist, its contents will be overwritten with the newly provided data, unless you specify that the data should be merged into the existing document

I experience that Visitor.NOTIFY_ON_CHAT_MESSAGE boolean is overwriting existing boolean at Cloud Firestore database Document. I though the SetOptions.merge() would not overwrite existing values? Maybe I missed something about how Transaction works or this is a Beta related thing since CF is Beta

like image 476
Erik Avatar asked Oct 27 '25 10:10

Erik


1 Answers

Regarding SetOptions merge() method as the official documentation says:

Changes the behavior of set() calls to only replace the values specified in its data argument. Fields omitted from the set() call will remain untouched.

So SetOptions.merge() method will only replace the fields under fieldPaths. Any field that is not specified in fieldPaths is ignored and remains untouched.

As a conslusion, if the document does not exist, it will be created. If the document does exist, its contents will be overwritten with the newly provided data, unless you specify that the data should be merged into the existing document, as follows:

// Update one field, creating the document if it does not already exist.
Map<String, Object> data = new HashMap<>();
data.put("Visitor.NOTIFY_ON_CHAT_MESSAGE", true);
docRefVisitor.set(data, SetOptions.merge());
like image 65
Alex Mamo Avatar answered Oct 29 '25 00:10

Alex Mamo