我正在尝试将用户添加到使用谷歌进行身份验证的实时数据库中,如下所示
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 登录的新用户没有添加到现有用户数据库而是添加到身份验证中时。
我不知道如何摆脱这个。
uj5u.com热心网友回复:
首先,正如@Frank 所评论的,必须有一个and/
之间。然后只采用Query(或DatabaseReference)型别的 1 个自变量,但您传递的是2,因此正在查询,这意味着整个数据库。默认情况下,数据库可能为空,因此第一个用户被添加,但之后将始终为真,并且不会添加新用户。'users'
userId
get()
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)
}
})
0 评论