如何在 Firebase Firestore 中使用用户"uid"创建文档



我正在尝试创建一个id为用户注册时id的文档

这是当用户注册时运行的功能->

const register = (e) => {
e.preventDefault();
auth
.createUserWithEmailAndPassword(email, password)
.then((auth) => {
if (auth) {
db.collection("users").add({
email: email,
password: password,
});
history.push("/");
}
})
.catch((error) => alert(error.message));
};

有人能帮助我如何通过.doc引用来实现这一点吗?

你能试试下面的代码吗?

const register = e => {
e.preventDefault();
auth
.createUserWithEmailAndPassword(email, password)
.then(credential => {
if (credential && credential.user) {
db.collection("users")
.doc(credential.user.uid)
.set({
email: email,
password: password
});
history.push("/");
}
})
.catch(error => alert(error.message));
};

参见:

  • https://firebase.google.com/docs/reference/js/firebase.auth.Auth#createuserwithemailandpassword
  • https://firebase.google.com/docs/reference/js/firebase.auth#usercredential
await db
.collection("users")
.add({ name: "baibhav", gender: "male" })
.then(async (docRef) => {
const ref = db.collection("users").doc(docRef.id)
ref
.update({ car: "Ferrari" })
.then(() => {
// updated
console.log("succeed")
})
.catch((err) => console.log(err))
})
.catch((err) => {
console.log(err)
})

你最好用一个";。添加";方法它自动生成文档id。并且您可以在提取文档后使用文档id。

把docRef.id扔到任何你必须使用的地方。并使用文档id调用更新方法。

最新更新