![](/img/trans.png)
[英]Firebase Firestore custom ID not creating new document after creating user properly
[英]Problem on creating Firestore document using Firebase user ID
全部。
我正在使用 Vue.js + Firebase 開發 web 應用程序。 在項目中,我正在開發一個注冊功能。
該功能基本上使用 firebase auth function 並且它工作正常。 作為一項附加功能,我需要在 Firestore 的“用戶”集合中創建一個文檔。 此處,文檔 ID 應與身份驗證 UID 相同。 但這並沒有按預期工作。 我只是需要一些幫助。
const firebaseApp = firebase.initializeApp(firebase_config)
const db = firebaseApp.firestore();
const auth = firebaseApp.auth();
export {db, auth};
import {db,auth} from '../plugins/firebase'
// ( omit ) //
methods: {
// this works
test: function(){
db.collection("users").doc("new_user").set({
displayName: "Bob",
}).catch(error=>{
console.log('error on debugging: ',error)
})
},
register: function(){
auth.createUserWithEmailAndPassword(this.user_mail, this.user_password)
.then(result=>{
// this works
console.log(result.user.uid)
// this does not work
db.collection('users').doc(result.user.uid).set({
displayName: 'John',
}).catch(error=>{
console.log('fail to add data: ',error)
})
})
.catch(error=>{
console.log('something goes wrong on auth: ',error)
})
}
}
Firestore 安全規則暫時如下。
match /{document=**} {
allow read, write, create: if request.auth.uid != null;
}
如果您使用的是AngularFire
庫,那么以下是寫入數據庫的方法。
import { AngularFirestore } from '@angular/fire/firestore';
constructor(
private angularFireStore: AngularFirestore,
) {}
methods: {
register: function(){
firebase.auth().createUserWithEmailAndPassword(this.user_mail, this.user_password)
.then(result=>{
// this works
console.log(result.user.uid)
const userUid = result.user.uid;
const data = {
displayName: 'John',
}
createUserDoc(userUid, data);
})
.catch(error=>{
console.log('something goes wrong on auth: ',error)
})
}
}
createUserDoc(userUid,userData){
return this.angularFireStore.collection('users').doc(userUid).set(userData);
}
以下應該可以解決問題。 如果在編寫用戶文檔時出現問題(例如,阻止它的安全規則),您應該在 catch 塊中看到它。
methods: {
// ...
register: function(){
auth.createUserWithEmailAndPassword(this.user_mail, this.user_password)
.then(result=>{
// this works
console.log(result.user.uid)
// this does not work
return db.collection('users').doc(result.user.uid).set({
displayName: 'John',
})
})
.catch(error=>{
console.log('something goes wrong on auth: ',error)
})
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.