'add/overwrite field of type array in Firestore

I want to add a field of type array inside a collection.

if the field doesn't exist create it. if it exists overwrite it with the new array value.

the field should be called macAddress and it's of type array of String

enter image description here

I have tried the following:

val macInput = setting_mac_text.text.toString()
            val macArray = macInput.split(",")
            val macList = Arrays.asList(macArray)
            val data =
                hashMapOf(Pair(FirebaseConstants.USER_MAC_ADDRESS, macArray))
            //save it in firebase
            db.collection(FirebaseConstants.ORGANIZATION)
                .document(orgID + ".${FirebaseConstants.USER_MAC_ADDRESS}")
                .set(FieldValue.arrayUnion(macList))
                .addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        Log.d(TAG, "successfully inserted")
                    } else {
                        Log.d(TAG, " failed ${task.exception}")
                    }
                }

also tried to insert the list itself and hash map like this

val data = hashMapOf(Pair(FirebaseConstants.USER_MAC_ADDRESS, macArray))
db.collection(FirebaseConstants.ORGANIZATION)
                .document(orgID)
                .set(data))

but it keeps giving me java.lang.IllegalArgumentException: Invalid data. Nested arrays are not supported

what am I doing wrong here?



Solution 1:[1]

To overwrite an array, you would simply call the set method and have the merge option set to true:

try {
  const query = await DatabaseService.queryBuilder({
    collection: CollectionName,
  });

  return await query
    .doc(insuranceId)
    .set(
      { DOCUMENT_PROPERTY_HERE: ARRAY_HERE },
      { merge: true }
    );
} catch (exception) {
  return Promise.reject(exception);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ajay