Home > Net >  How can I store documents in firestore database without overwritting the data?
How can I store documents in firestore database without overwritting the data?

Time:08-05

I want to store "val credentials" inside "Credenciales" and "val generales" within "Generales" for each user in the firestore. However, if I sign up as a new user, it overwrites the stored data of the old user. Please, let me know how I can store both variables without replacing them.

Here's my snipped code:

val generales = hashMapOf(
    "Nombre" to nameEditText.text.toString(),
    "Celular" to celularEditText.text.toString(),
    "Cedula" to cedulaEditText.text.toString(),
    "Oficio" to oficioEditText.text.toString(),
    "Estado civil" to auto_complete_txt.text.toString(),
    "Calle" to calleEditText.text.toString(),
    "Sector" to sectorEditText.text.toString(),
    "Edificio" to edificioEditText.text.toString(),
    "Apto" to numeroEditText.text.toString(),
    "Ciudad" to ciudadEditText.text.toString(),
    "Residencial" to resEditText.text.toString(),
    "Telefono" to telEditText.text.toString(),
    )

    db.collection("Usuarios").document("Generales")
        .set(datos)

val credentials = hashMapOf(
    "email" to emailEditText.text.toString(),
    "password" to passwordEditText.text.toString(),
        )

     db.collection("Usuarios").document("Credenciales")
       .set(credentials)

Update:

val generales = hashMapOf(
        "Nombre" to nameEditText.text.toString(),
        "Celular" to celularEditText.text.toString(),
        "Cedula" to cedulaEditText.text.toString(),
        "Oficio" to oficioEditText.text.toString(),
        "Estado civil" to auto_complete_txt.text.toString(),
        "Calle" to calleEditText.text.toString(),
        "Sector" to sectorEditText.text.toString(),
        "Edificio" to edificioEditText.text.toString(),
        "Apto" to numeroEditText.text.toString(),
        "Ciudad" to ciudadEditText.text.toString(),
        "Residencial" to resEditText.text.toString(),
        "Telefono" to telEditText.text.toString(),
    )


    // Add a new document with a generated ID
    db.collection("Usuarios").document("Credenciales")
        **.add(generales)** // I get an unresolved reference error here.
        .addOnSuccessListener { documentReference ->
            Log.d(TAG, "DocumentSnapshot written with ID: Generales")
        }
        .addOnFailureListener { e ->
            Log.w(TAG, "Error adding document", e)
        }

CodePudding user response:

You need to remove the .document("Credenciales") when adding and just have it as:

db.collection("Usuarios").add(generales) //etc.

of if you want to add to a sub collection it will be something like:

db.collection("Usuarios").doc(docref).collection(subcollectionRef).add(generales)
  • Related