'How to create a new table inserting a variable into .doc()

I've created a SignIn page that allocates its data on variables using document.getElementByClassName. So I'm trying to create a new document on Firebase using the person's name, stored on a variable (which could bring some problems) using -- .doc(variableHere) -- but I didn't manage to find a way.

let newUserPrimeiroNome = document.getElementsByClassName("primeiroNome");
let newUserSobrenome = document.getElementsByClassName("ultimoNome");
let newUserEmail = document.getElementsByClassName("email");
let newUserPassword = document.getElementsByClassName("senha");

let btn = document.getElementById("btn");
btn.addEventListener("click", criaNovoUsuario);

function criaNovoUsuario() {
        db.collection("loginsSecretaria").doc(newUserPrimeiroNome) // <- error here
        .add({
            primeiroNome: newUserPrimeiroNome[0].value,
            ultimoNome: newUserSobrenome[0].value,
            email: newUserEmail[0].value,
            senha: newUserPassword[0].value
        }).then(() => {
            console.log("Documento inserido com sucesso");
        }).catch((error) => {
            console.log("Erro ao inserir documento: ", error);
        });
}

ps.: I'm sorry if I didn't express myself in very clear way



Solution 1:[1]

Any variable should work as long as the variable is a string (not an object/array) and doesn't match any of the constraints documented by Google. Your issue here was that you're calling getElementsByClassName which returns an array of elements. You need the value of the first element, which you can get via newUserPrimeiroNome[0].value...

Note, however, that using a first name as an ID probably isn't the best approach since it's not likely to be unique. Two users could both have the name John, for example, and then you wouldn't have a unique document for each of them... you also probably want to do some data validation before you try to use user-created input as a document ID.

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