0

I have a PUT: /users endpoint which takes multiple fields. In most cases I want to just call .set on the document with {merge: true} to be able to update individual document-fields without removing others. but in another case I was to update a map to only have one value within it.

for example:

// user doc
displayName: 'Frank'
age: 28
gender: {
  male: true
}
orientation: {
  female: true
}

displayName & age are fine to be merged but when it comes to gender & orientation i want to flat-out replace the map with a new one. i know I could have a property of gender: 'male' but this doesn't allow for scalable querying as I am building a dating app and need to have an as flexible as possible query-base.

At the moment say I was to call ...doc.set({ gender: {female: true} }, {merge: true}); My document structure would look like:

displayName: 'Frank'
age: 28
gender: {
  male: true,
  female: true,
}
orientation: {
  female: true
}

But ideally it would just fully replace the gender map altogether. i.e

displayName: 'Frank'
age: 28
gender: {
  female: true
}
orientation: {
  female: true
}

Has anyone any experience with this? Again I want to keep this structure as a Map so that I can run queries like

db
  .collection('users')
  .where(`gender.${myOrientation}`, '==', true)
  .where('gender.all', '==', true) <-- for non-gender-specific users

I am also aware of the array structure but firestore-queries are limited to 1 array query per query.

Thank you!

Francis Leigh
  • 1,870
  • 10
  • 25

1 Answers1

1

Would it not be better to use update instead of set with merge? Using this:

      var userDoc = db.collection('users').doc(docId);
      userDoc.update({ gender: {female: true} });

You will get the exact result you need.

Here there is a Stack Overflow thread that explains the differences between using update or set with merge in Cloud Firestore. In one answer, there is also an example about merge:true behaviour in nested fields.

DamPlz
  • 140
  • 6