如何从Firebase文档中读取值并与变量进行比较,然后更改文档的值

时间:2019-04-04 04:23:54

标签: firebase react-native mobile firebase-authentication

我正在尝试让用户使用验证码确认其帐户。我想从firestore数据库中获取用户文档,检查以确保身份验证代码与提供的值匹配,然后将文档的hasVerfied字段更改为True。

这是针对移动应用程序(在设备上,而不是在服务器端),所以我不能使用firebase-admin ...我有一个屏幕出现,但是一旦填写了身份验证字段,请单击该按钮,则不会执行任何操作,但是我可以确认该函数肯定已到达,只是由于某些错误而不在其中执行代码。

handleConfirmation = () => {
  const auth_code = this.state.authCode;
  let user = firebase.firestore().collection('users').where('uid', '==', firebase.auth().currentUser.uid);
  // ^ I am not sure if this is correct... could be a source of wrongness.
  if (user.exists === true) {
            console.log(user.data());
            let user_to_verify = user.data();
            const has_verified = user_to_verify.hasVerified;
            if (has_verified === false) {
                const user_auth_code = user.authCode;
                if (auth_code === user_auth_code) {
                    console.log("User verification code is correct");
                    this.setState({hasVerified: true});
                    this.updateUser();
                    // ^ this function should set the 
                   // value of user.hasVerified to True, and 
                  // save it in firestore (aka firebase firestore) 
                 //
                // Now the user can successfully login to app 

                }
  }else{
  // user doesnt exist... throw error and exit

  }

提交表单时(应用中按钮的onPress)handleConfirmation会执行,并将auth_code与user_auth_code(这是firebase firestore文档中authCode字段的值)进行比较,如果这些值匹配,则用户的hasVerified字段更改为True并保存在firebase中。

请帮助!仅供参考,这是我有史以来第一次在StackOverFlow上发帖,所以请告诉我是否遵循正确的指南。

// EDIT:显示创建时如何初始化用户。

constructor() {
        super();
        this.ref = firebase.firestore().collection('users');
        this.state =
            {
                firstname: '<first name>',
                lastname: '<last name>',
                email: '<email>',
                password: '<password>',
                errorMessage: '<none unless error occurs>',
                secureTextEntry: true,
                confirmPassword: '<password>',
                modalVisible: false,
                imageURI: '<some url>',
                authCode: '<authentication code>',
                hasVerified: false,

            };
        this._keyboardDidHide = this._keyboardDidHide.bind(this);
        this.setDate = this.setDate.bind(this);
    }
.
.  // SKIPPED SOME IN-BETWEEN LINES FOR BREVITY
.

updateUser() {
        let user_data = {
            uid: firebase.auth().currentUser.uid,
            firstname: this.state.firstname,
            lastname: this.state.lastname,
            email: this.state.email,
            imageURI: this.state.imageURI,
            authCode: this.state.authCode,
            hasVerified: this.state.hasVerified,
        };
        console.log(user_data);
        this.ref.doc(firebase.auth().currentUser.uid).set(user_data);
        this.props.navigation.navigate('homescreen');
    }

1 个答案:

答案 0 :(得分:0)

签出以下代码,

您必须将文档的doc-ID存储在文档中,以便在以后的阶段中使用updateUser。最后,我给出了一个示例,说明了如何做。

handleConfirmation = () => {
const auth_code = this.state.authCode;
  var user = firebase
    .firestore()
    .collection("users")
    .where("uid", "==", firebase.auth().currentUser.uid)
    .get()
    .then(querySnapshot => {
      if (querySnapshot._docs.length > 0) { // User exists !!
        console.log(querySnapshot._docs);
        // You require the doc_Id of the document so that you can update it in the later stage.
        const has_verified = querySnapshot._docs[0]._data.hasVerified; //_docs is a array, considering there is only 1 unique user
        if (has_verified == false) {
          const user_auth_code = querySnapshot._docs[0]._data.authCode; // or use firebase.auth().currentUser.uid instead.
          if (auth_code === user_auth_code) {
            console.log("User verification code is correct");
            this.setState({ hasVerified: true });
            this.updateUser(querySnapshot._docs[0]._data.doc_Id); // As told above doc_ID is required
          }
        }
      }
    });
};

updateUser = doc_id => {
  var user = firebase
    .firestore()
    .collection("users")
    .doc(doc_id)
    .set({
      hasVerified: true
    });
};

//Example for adding doc_ID in document during document creation. Make sure you do this process during user creation.
//The below code is for your reference.

exampleDocCreate = () => {
  var user = firebase
    .firestore()
    .collection("users")
    .add({
      userName: "React Native User"
    })
    .then(data => {
      var user = firebase
        .firestore()
        .collection("users")
        .doc(data.id)
        .set({
          doc_id: data.id
        });
    });
};

根据我的理解,您正在寻找一种方法, 1)找到一个存在的用户。 2)如果存在,则获取其hasVerified和authCode信息。 3)在集合中比较并更新其文档。

希望我能帮助您