Firebase 实时数据库添加 google 个经过身份验证的用户

Firebase relatime database add google authenticated users

我正在尝试将使用 google 进行身份验证的用户添加到实时数据库,如下所示

document.getElementById("btnGoogleLogin").addEventListener('click', function () {
    signInWithPopup(auth, provider)
        .then((result) => {
            // This gives you a Google Access Token. You can use it to access the Google API.
            const credential = GoogleAuthProvider.credentialFromResult(result);
            const token = credential.accessToken;
           
            // The signed-in user info.
            const user = result.user;
       
            const userId = user.uid;
            const email = user.email;
            const imageUrl = user.photoURL;
            const name = user.displayName;

            const dbRef = ref(database);
            console.log("Current User:" + userId);
            get(dbRef, '/users' + userId).then((snapshot) => {
                if (snapshot.exists()) {
                    console.log(snapshot.val());
                } else {
                    console.log("First time user..Need to add it to db");
                    writeUserData(userId, email, imageUrl, name)
                }
            }).catch((error) => {
                console.error(error);
            });

        }).catch((error) => {
            // Handle Errors here.
            const errorCode = error.code;
            const errorMessage = error.message;
            // The email of the user's account used.
            const email = error.email;
            // The AuthCredential type that was used.
            const credential = GoogleAuthProvider.credentialFromError(error);
            console.log(error);
        });
});


function writeUserData(userId, email, imageUrl, name) {
    set(ref(database, '/' + userId), {
        email: email,
        imageUrl: imageUrl,
        name: name
    })
        .then(() => {
            window.location.href = "https://www.mysite.default.html";
        })
        .catch((error) => {
            // The write failed...
        });
}

问题是第一次在用户数据库下添加用户时,当使用 google 登录的新用户没有被添加到现有用户数据库中,而是添加到身份验证中时。

我不知道如何摆脱它。

首先正如@Frank 所说,'users'userId 之间必须有一个/。然后 get() 仅采用 1 个 Query (or a DatabaseReference) 类型的参数,但您传递的是 2 个,因此 get() 正在查询 dbRef,这意味着整个数据库。默认情况下,数据库可能为空,因此会添加第一个用户,但在 snapshot.exists() 之后将始终为真,不会添加新用户。

使用 child() 创建 DatabaseReference 应该可以解决这个问题:

import { child, get } from "firebase/database"

const userRef = child(dbRef, 'users/' + userId);

get(userRef).then((snapshot) => {
  if (snapshot.exists()) {
    console.log(snapshot.val());
  } else {
    console.log("First time user..Need to add it to db");
    writeUserData(userId, email, imageUrl, name)
  }
})