我是React Native和Firestore的新手。我不明白为什么我的文档引用id在控制台日志中一直显示为未定义,但Firestore数据库中有一个id。我只是想捕捉id,这样我就可以在另一个屏幕上使用它,并在文档中添加更多字段。这是我的代码示例:
const handleSignUp = () => {
createUserWithEmailAndPassword(auth, email, password)
.then((userCredentials) => {
const user = userCredentials.user;
console.log("Registered with: ", user.email);
console.log("Welcome", name);
try {
const docRef = addDoc(collection(db, "userInfo"), {
fullname: name,
userID: uID,
});
console.log("Success writing document!", docRef.id, "yay");
} catch (e) {
console.error("Error adding document: ", e);
}
})
.catch((error) => alert(error.message));
};
由于addDoc
返回一个promise,因此需要使用await
或then
。
const handleSignUp = () => {
createUserWithEmailAndPassword(auth, email, password)
.then(async (userCredentials) => { // make function async
const user = userCredentials.user;
console.log("Registered with: ", user.email);
console.log("Welcome", name);
try {
const docRef = await addDoc(collection(db, "userInfo"), { // here you need to use await
fullname: name,
userID: uID,
});
console.log("Success writing document!", docRef.id, "yay");
} catch (e) {
console.error("Error adding document: ", e);
}
})
.catch((error) => alert(error.message));
有关谷歌文档的更多信息:https://firebase.google.com/docs/firestore/manage-data/add-data#add_a_document