Javascript 如何在firestore文档ID的位置添加用户UID
我正在尝试在Firebase/Firestore中获取用户UID以代替自动生成的文档ID,但由于此错误而无法获取 TypeError:firebase.auth(…).currentUser为null 这是我的index.js文件:-Javascript 如何在firestore文档ID的位置添加用户UID,javascript,firebase,firebase-authentication,google-cloud-firestore,Javascript,Firebase,Firebase Authentication,Google Cloud Firestore,我正在尝试在Firebase/Firestore中获取用户UID以代替自动生成的文档ID,但由于此错误而无法获取 TypeError:firebase.auth(…).currentUser为null 这是我的index.js文件:- // Firestore Cloud Database var db = firebase.firestore(); function reg(){ //window.alert("Working..!"); const txtname = document.g
// Firestore Cloud Database
var db = firebase.firestore();
function reg(){
//window.alert("Working..!");
const txtname = document.getElementById('txtuname').value;
const txtEmail = document.getElementById('txtemail').value;
const txtPass = document.getElementById('txtpass').value;
//window.alert(txtname);
firebase.auth().createUserWithEmailAndPassword(txtEmail, txtPass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
//alert(errorMessage);
}
console.log(error);
// [END_EXCLUDE]
});
// Getting user id
var uid = firebase.auth().currentUser.uid;
//User Data Insertion
if(uid !=null){
db.collection("users").doc(uid).add({
UserName: txtname,
Email: txtEmail,
Password: txtPass
})
// .then(function(uid) {
// console.log("Document written with ID: ", uid);
// })
.catch(function(error) {
console.error("Error adding document: ", error);
});
}
}
由于firebase.auth().createUserWithEmailAndPassword(…)
是一个异步函数,因此必须等待解析后才能继续
您可以尝试以下方法:
// Firestore Cloud Database
var db = firebase.firestore();
function reg(){
//window.alert("Working..!");
const txtname = document.getElementById('txtuname').value;
const txtEmail = document.getElementById('txtemail').value;
const txtPass = document.getElementById('txtpass').value;
//window.alert(txtname);
firebase.auth().createUserWithEmailAndPassword(txtEmail,txtPass)
.then(function (user) {
// insert any document you want here
})
.catch(function(error) {
// handle error here
});
}
在我向大家介绍我的答案之前,请注意,云功能确实需要不可预测的时间来处理。因此,如果您需要立即开始使用存储在users集合中的数据,那么这可能不是您应该采用的正确方法 使用firebase云函数
exports.createUser = functions.auth.user().onCreate((user) => {
const userMap = {
uid: user.uid,
email: user.email,
};
return admin.firestore().collection('user').doc(user.uid).set(userMap);
});
您可以关联下面的示例并生成代码 这里的
“\u email”、“\u password”、“\u city”、“\u phone”
是
onSaved:(value)=>\u email=value
取自TextFormField()
函数
代码:
String userId = await widget.auth.createUserWithEmailAndPassword(_email, _password);
print('Registered user: $userId');
final new_user = await FirebaseFirestore.instance.collection('users').doc(userId).
set({"UserUID":'$userId',"Email":_email,"Password":_password,"City":_city,"Phone
Number":_phone});
首先是一些个人提示:正确的代码缩进使它更容易阅读(对我来说)。其次,在创建新用户时,您似乎正在尝试在firestore中添加一些数据。在这种情况下,您必须确保firebase已完成创建用途:查看感谢您的帮助