[英]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.