简体   繁体   English

在 Firebase 注册后立即将用户信息保存到数据库中

[英]Save user info into database just after registration in Firebase

I am trying to save a newly created user's info into Firestore using the uid as the document id.我正在尝试使用 uid 作为文档 ID 将新创建的用户信息保存到 Firestore 中。 The problem I encounter comes after the creation of the user, in order to save his information into the Firestore collection after creation.我遇到的问题是在创建用户之后,为了在创建后将他的信息保存到Firestore集合中。 Here is what I have already tried:这是我已经尝试过的:

 const usersRef = firebase.firestore().collection('Users');

 firebase.auth().createUserWithEmailAndPassword(values.email, values.password).then(function(user){
  usersRef.doc(`${user.uid}`).set({
    firstName: values.firstName,
    lastName: values.lastName,
    username: values.username,
    uid: user.uid
  })
}).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]
});

The code is expected to save the user's info after creation, but it causes the following error : The collection document ID cannot be undefined or so该代码预计会在创建后保存用户信息,但会导致以下错误:集合文档 ID 不能未定义等

The method you're using using returns Promise<UserCredential> .您使用的方法返回Promise<UserCredential> Your code should be:你的代码应该是:

const usersRef = firebase
  .firestore()
  .collection('Users');

firebase
  .auth()
  .createUserWithEmailAndPassword(values.email, values.password)
  .then(function(userCredential) {
    usersRef
      .doc(`${userCredential.user.uid}`)
      .set({
        firstName: values.firstName,
        lastName: values.lastName,
        username: values.username,
        uid: userCredential.user.uid
      })
      ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM