Home > Software design >  Firestore: how to specify the firestore key to be used for merge?
Firestore: how to specify the firestore key to be used for merge?

Time:07-13

I have a function written in nodejs and another in python. They both do the same thing in different scripts.

I currently have a function that creates a firestore collection called profile, then insert a document, which has as a name, the document id created by firestore

The document itself contains an object, representing the user, first name, last name, email, and phone.

the phone is a list, or array [], it always contains just one phone number, later on we'll add multiple phone numbers per user but for now, you can assume that there is just one element in a list. Phone can never be null, email can be null sometimes.

What I want to do, is if the phone doesn't exist already then insert a new user, otherwise update the existing user. So there should be no duplication.

Can this be done via merge in firestore or update or should I do a where query? I know that a query is always possible, but I want to know if I can use a merge on a list field in firestore.

CodePudding user response:

If you don't have any document reference to update to and need to query the field phone_number then you need to use the where() method with the array_contains operator. Use the array_contains operator to filter based on array values. If a document is found you can use arrayUnion() to add elements to an array but only elements are not already present. See sample snippets below:

Python:

# Collection Reference
col_ref = db.collection(u'profile')
# Check collection if there's any array in documents that contains the `phone_number`
admin_ref = col_ref.where(u'phone_number', u'array_contains', 12345).get()

# Checks if there's a result.
if admin_ref:
  # Iterate the result 
  for item in admin_ref:
    doc = col_ref.document(item.id)
    doc.update(
      # Adds multiple phone numbers to the field, but only adds new ones.
      {u'phone_number': firestore.ArrayUnion([12345,54321])})
# If there's no result, then add a document with the field name `phone_number`
else:
  col_ref.add({'phone_number': [123456]})

For more information, you can check these documentations:

  • Related