Difference between merge and mergeFields in Firebase Firestore

This is how I interpreted it. IF merge = true is specified to a set operation THEN it is like Object.assign(firestoreDoc, yourpayload). For example, if firebaseDoc contents are like this:

{
  name:'batman',
  city: 'gotham',
  isLeagueMember: true
}

And your payload (JSON) content is like this:

{
  isLeageMember:false,
  reason:'gone rogue'
}

After the set operation with merge=true the firestoreDoc will look like

{
  name:'batman',
  city: 'gotham',
  isLeagueMember: false,
  reason:'gone rogue'
}

On the other hand, for mergeFields you would specify the set of fields to update. So if I take the above example but this time set operation with merge fields options [name, reason] then the result (firebaseDoc after set completion) will be:

{
  name:'batman',
  city: 'gotham',
  isLeagueMember: true,
  reason:'gone rogue'
}

This was somewhat confusing to me too until I found the biggest clue is merge is a boolean and mergeFields is an array.

This is very handy for batched operations.

Hope this helps. Thank you.


One important thing to note; { merge: true } has a somewhat strange interaction if you ask me. If an inner object is empty, it will replace the existing inner object. However if it's not empty, it will update the specified property in the inner object and leave the rest alone.

E.g. set({ innerObject: {}, { merge: true })

to existing { innerObject: { someKey: 'someValue' } }

would result in { innerObject: {} }

However

set({ innerObject: { someOtherKey: 'someOtherValue' }, { merge: true })

to existing { innerObject: { someKey: 'someValue' } }

would result in { innerObject: { someKey: 'someValue', someOtherKey: 'someOtherValue' } }

So make sure to clean out empty inner objects unless you want to delete them from the document.