首页 > 解决方案 > 在firebase中创建用户后获取用户ID

问题描述

我正在尝试在我的网站上检索新创建用户的 ID。管理员根据用户的电子邮件和密码创建帐户。但是一旦创建了帐户,我就需要该 id 并将其在 firestore 数据库中用作文档 id 来存储用户信息。这就是我的代码的样子:

firebase.auth().createUserWithEmailAndPassword(email.trim(), password.trim())
            .then(function () {
                db.collection("users").add({
                    email: email.trim(),
                    name: username.trim(),
                    id: //I need the user's id here
                }).then(function () {
                    window.alert('User registered successfully');
                    window.location = 'user.html';
                }).catch(function (error) {
                    window.alert("There was some error. Please try again.");
                    console.log(error.code);
                    console.log(error.message);
                });
            })

有没有办法让我在那个部分获得该用户的 ID?

标签: javascriptfirebasefirebase-authentication

解决方案


你可以试试这个:

firebase.auth().createUserWithEmailAndPassword(email, password)
.then((userCredential) => {  // the userCredential is a variable that will hold the response in it, it contains all the user info in it
    // Signed in
    var user = userCredential.user;
    // This user variable contains all the info related to user including its id
})
.catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
});

参考


推荐阅读