[英]How do I check if a document exists within a collection (Firebase REACT)?
[英]How do I add value to a document that is expected to be created? (Firebase + React)
我想在創建它時向 firebase 用戶的文檔添加一個字段(用戶名)。
我的邏輯:
錯誤:未處理的錯誤 { 錯誤:5 NOT_FOUND:沒有要更新的文檔:projects/yeu/databases/(默認)/documents/users/DchYhQNMS12VYqzSwtEZ8UXYhcD3
我知道沒有文件(還沒有) - 所以我的問題是我如何確保文件在需要時准備好。
代碼:
ReactJS - 注冊事件,(使用表單和 OnClick)
export function SignUp() {
const handleSignupSubmit = (event) => {
event.preventDefault();
const registerForm = document.querySelector(".register");
// firebase
const addUserName = firebase.functions().httpsCallable("addUserName");
// register form
const email = registerForm.email.value;
const password = registerForm.password.value;
const fullName = registerForm.fullName.value;
// firebase sign up
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((userAuth) => {
console.log("registered", userAuth);
addUserName({
userName : fullName
}).then(((doc)=>{
console.log("UserName Added", doc);
}))
.catch((error) => {
registerForm.reset();
registerForm.querySelector(".error").textContent = error.message;
});
})
.catch((error) => {
registerForm.querySelector(".error").textContent = error.message;
});
};
Firebase 后端 - 身份驗證觸發器
// auth trigger (new user signup)
exports.newUserSignUp = functions.auth.user().onCreate((user) => {
// for background triggers you must return a value/promise
return admin.firestore().collection("users").doc(user.uid).set({
userName: 'Temp',
email: user.email,
});
});
Firebase 后端 - HTTP 可調用方法
// http callable function (adding a username)
exports.addUserName = functions.https.onCall((data, context) => {
if (!context.auth) {
throw new functions.https.HttpsError("unauthenticated");
}
const userRef = admin.firestore().collection("users").doc(context.auth.uid);
return userRef.get().then((doc) => {
return userRef.update({
userName: data.userName
})
})
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.