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

问题描述 投票:1回答:1

我正在尝试让用户使用验证码确认其帐户。我想从firestore db获取用户文档,检查以确保验证代码与提供的值匹配,然后将文档的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字段将更改为真实并保存在firebase中。

请帮忙!仅供参考,这是我在StackOverFlow上发表的第一篇文章,请告诉我是否遵循了正确的指导原则。

//编辑:显示我在创建时如何初始化用户。

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');
    }
firebase react-native mobile firebase-authentication
1个回答
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)比较和更新集合中的文档。

我希望我能帮助你

© www.soinside.com 2019 - 2024. All rights reserved.