简体   繁体   English

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

[英]How to read a value from Firebase document and compare with variable, then change document's value

I am trying have a user confirm their account using a verification code. 我正在尝试让用户使用验证码确认其帐户。 I want to get the user document from the firestore db, check to ensure the authentication code matches the value provided, and then changed the hasVerfied field of the document to True. 我想从firestore数据库中获取用户文档,检查以确保身份验证代码与提供的值匹配,然后将文档的hasVerfied字段更改为True。

This is for a mobile application (on device, not server-side) so I can not use firebase-admin... I have a screen appearing but once I fill out the authentication field click the button no action occurs, but I can confirm that the function is definitely being reached, just not executing the code within because of some error. 这是针对移动应用程序(在设备上,而不是服务器端)的,因此我无法使用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

  }

on submission of form (onPress of button in app) handleConfirmation is executed and the auth_code is compared to user_auth_code (which is the value of the authCode field from the firebase firestore document), if these values match, the hasVerified field of user is changed to True and saved in firebase. 在提交表单时(应用中按钮的onPress)执行handleConfirmation并将auth_code与user_auth_code(这是firebase firestore文档中authCode字段的值)进行比较,如果这些值匹配,则用户的hasVerified字段将更改为正确,并保存在Firebase中。

Please help! 请帮忙! FYI this is my first ever post on StackOverFlow so let me know if I followed the proper guidelines. 仅供参考,这是我有史以来第一次在StackOverFlow上发帖,所以请告诉我是否遵循正确的指导原则。

//EDIT: showing how I initialize users upon creation. //编辑:显示我如何在创建时初始化用户。

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');
    }

Checkout the below code, 签出以下代码,

You have to store the doc-ID of the document inside the document to updateUser in later stages. 您必须将文档的doc-ID存储在文档中,以便在以后的阶段中使用updateUser。 I have given an example of how to do it as well in the last. 我在最后给出了一个如何做的例子。

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
        });
    });
};

As per my understanding you are looking for a way to, 1) find a user who exists. 根据我的理解,您正在寻找一种方法,1)找到一个存在的用户。 2) If exists grab their hasVerified and authCode information. 2)如果存在,则获取其hasVerified和authCode信息。 3) Compare and Update the their Document inside the Collection. 3)在集合中比较并更新其文档。

I hope I could help you 希望可以帮到您

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

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