Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between merge and mergeFields in Firebase Firestore

I can a data to the Firebase Firestore document through the following methods:

1) add()

2) set()

I am very clear that how can i add data to Firestore, there is no confusion in it. But my question there is two setOption for the method 'set' in Firebase Firestore, such that merge and mergefields. What is the difference between these two set options, I think both options are doing same job. How can I implement setOption 'mergeFIeld'? I can't find any documentation for it.

like image 548
pepe Avatar asked Apr 26 '19 18:04

pepe


2 Answers

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.

like image 88
Ali Nahid Avatar answered Nov 20 '22 20:11

Ali Nahid


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.

like image 4
Bumpfel Avatar answered Nov 20 '22 22:11

Bumpfel