Check for duplicates before saving them on database

Hello everyone,
I’m pretty new to coding and to Velo, therefore I need help.
I created a member’s page, the page gets the pricing plan that the member subscribed to, and it shows a specific form to be submitted in order to set a dashboard according to the region he/she selects.
When the user submits the form, my code checks for duplicates like email and field values. If the user has already submitted it an error will appear telling the user that the form was already submitted, if the value is “” or equal to another one, another message will appear and tells the user to check the selection and make 3 different selections.
Well for the Free Plan where only one dropdown is shown, everything runs smoothly, for the Basic where I have 3 dropdowns nothing works. So… let’ go to the code:

import wixData from ‘wix-data’ ;
import wixUsers from ‘wix-users’ ;

$w . onReady ( function () {

    console . log ( "Ready" ) 

    **let**  user  =  wixUsers . currentUser 

    user . getPricingPlans ()  
    . then  (( pricingPlans ) => { 

     **let**  firstPlan  =  pricingPlans [ 0 ]; 
     **let**   planName  =  firstPlan . name ; 

     **if**  ( planName  ==  '7 DAY FREE TRIAL $0' ){   
     $w ( '#text30' ). show (); 
     $w ( "#text31" ). show (); 
     $w ( '#dropdown1' ). show (); 
     $w ( '#emailInput' ). show (); 
     $w ( '#button1' ). show (); 
     
     searchForDuplicityFreePlan (); 
     } 

     **if** ( planName  ==  'BASIC' ){ 
     $w ( '#text30' ). show (); 
     $w ( "#text31" ). show (); 
     $w ( '#dropdown2' ). show (); 
     $w ( '#dropdown3' ). show (); 
     $w ( '#dropdown4' ). show (); 
     $w ( '#emailInput2' ). show (); 
     $w ( '#button2' ). show (); 

     searchForDuplicityBasicPlan (); 

    }   

    });  

});

async function searchForDuplicityFreePlan (){

    $w ( "#dataset1" ). onBeforeSave ( **async** () => { 

            **let**  checkEmailFreeOk  =  **await**  checkEmailFree (); 
            **let**  fieldCheck  =  $w ( "#dropdown1" ). value ; 

            **if** ( checkEmailFreeOk  ===  **false** ){ 
                    $w ( "#text32" ). text  =  "An error occurred. You have already submitted this form" ; 
               **return**  **false**      
            } 

            **if** ( fieldCheck  ===  "" ){ 
                  $w ( "#text32" ). text  =  "An error occurred. Please select your region of interest" ; 
               **return**  **false**        
            } 

    }) 

}

async function checkEmailFree (){

    **let**  flagFree  =  **true** 

    **await**  wixData . query ( 'RegionSelectionQuizFree' ) 
    . eq ( 'email' ,  $w ( "#emailInput" ). value ) 
    . find () 
    . then (( result )=>{ 

         **if** ( result . items . length  >  0 )    

         flagFree  =  **false** 

    }) 

    **return**  **await**  flagFree 

}

async function searchForDuplicityBasicPlan (){

    $w ( "#dataset2" ). onBeforeSave ( **async** () => { 

            **let**  checkEmailBasicOk  =  **await**  checkEmailBasic (); 
            **let**  region1  =  $w ( "#dropdown2" ). value ; 
            **let**  region2  =  $w ( "#dropdown3" ). value ; 
            **let**  region3  =  $w ( "#dropdown4" ). value ; 

            **const**  regions  =  **new**  Set (); 
            regions . add ( region1 ); 
            regions . add ( region2 ); 
            regions . add ( region3 );                 
            regions . **delete** ( "" );  
           
            **if** ( checkEmailBasicOk  ===  **false** ){ 
                    $w ( "#text34" ). text  =  "An error occurred. You have already submitted this form" ; 
                    **return**  **false**      
            }  

            **if**  ( regions . size  !==  3 ) { 
                $w ( "#text34" ). text  =  "An error occurred. Please select 3 different regions of interest" ; 
                **return**  **false**              
            } 

    }) 

}

async function checkEmailBasic (){

    **let**  flagBasic  =  **true** 

    **await**  wixData . query ( 'RegionSelectionQuizBasic' ) 
    . eq ( 'email' ,  $w ( "#emailInput2" ). value ) 
    . find () 
    . then (( result )=>{ 

         **if** ( result . items . length  >  0 )    

         flagBasic  =  **false** 
    }) 

    **return**  **await**  flagBasic 

}

The rest you will have to improve by your own…
Take a look onto console and try to inspect your own code.
Follow the logical console-infos…
Add your own console-logs, to inspect and understand your own code even better.

import wixData from 'wix-data';
import wixUsers from 'wix-users';

$w.onReady(function() {console.log("Page-Ready!")
  let user = wixUsers.currentUser; console.log("USER: ", user);
  user.getPricingPlans() 
  .then((pricingPlans)=> {console.log("Pricing-Plans: ", pricingPlans);
    let firstPlan = pricingPlans[0];  console.log("First-Plan: ", firstPlan);
    let  planName = firstPlan.name;   console.log("Plan-Name: ", planName);

    if (planName == '7 DAY FREE TRIAL $0'){  
      $w('#text30, #text31').show();
      $w('#dropdown1, #emailInput, #button1').show();
      //searchForDuplicityFreePlan();
      
      $w("#dataset1").onBeforeSave(async()=> {
        let checkEmailFreeOk = await checkDatabase('RegionSelectionQuizFree', 'email', $w("#emailInput").value);
        let fieldCheck = $w("#dropdown1").value;

        if(checkEmailFreeOk === false){
                $w("#text32").text = "An error occurred. You have already submitted this form";
            return false     
        }
        if(fieldCheck === ""){
              $w("#text32").text = "An error occurred. Please select your region of interest";
            return false       
        }
      });
    }
    

    if(planName == 'BASIC'){
      $w('#text30, #text31, #emailInput2, #button2').show();
      $w('#dropdown2, #dropdown3, #dropdown4').show();
      //searchForDuplicityBasicPlan();


      $w("#dataset2").onBeforeSave(async() => {
        let checkEmailBasicOk = await checkDatabase('RegionSelectionQuizBasic', 'email', $w("#emailInput2").value);
        let region1 = $w("#dropdown2").value;
        let region2 = $w("#dropdown3").value;
        let region3 = $w("#dropdown4").value;

        const regions = new Set();
        regions.add(region1);
        regions.add(region2);
        regions.add(region3);                
        regions.delete(""); 
        
        if(checkEmailBasicOk === false){
          $w("#text34").text = "An error occurred. You have already submitted this form";
          return false     
        } 

        if (regions.size !== 3) {
          $w("#text34").text = "An error occurred. Please select 3 different regions of interest";
          return false             
        }
      })
    }        
  }); 
});



function checkDatabase(collection, dbField, value) {
  wixData.query(collection)
  .eq(dbField, value)
  .find()
  .then((res)=>{console.log("RESULTS: ", res);
    if(res.items.length>0)  {return false} 
    else {return true}
  }).catch((err)=>{console.log(err);});
}

Thank you so much for your time in trying to solve the issue, but even with your code suggestions it ends up in the same result. The first form work without any problem, the query retrieves a result and blocks the submission if the result matches. In the basic form, it doesn’t work. The dropdowns correlations are in order and don’t allow duplicates, but the query doesn’t work even though it is the same code used for the free form… bizarre.

@sabrinaamazon
As already mentioned, my provided code was not completely debuged.

The rest you will have to improve by your own…

Take a look onto console and try to inspect your own code.

Follow the logical console-infos…

Add your own console-logs, to inspect and understand your own code even better.

If you still are not able to solve it → than feel free to ask for a second helping hand. But first try to do it by your own. Learning by doing is the best method to learn something.

@russian-dima as I told you, I did the corrections needed, so your code could work, but I got the same results. To follow the logical console logs, I have to be able to inspect it, which is not possible since the same error is shown when I try.

@sabrinaamazon This error indicates that you should test in live mode. For console message in browser choose developer tools option.

Also, I recommend to use dataHooks. The similar example is also available in Wix examples.

@sabrinaamazon
As Rajjat Garg already mentioned, run your code on a LIVE-SITE.
If you are using Google-ChromePRESS F-12 and navigate to → CONSOLE .

import wixData from 'wix-data';
import wixUsers from 'wix-users';

$w.onReady(function() {console.log("Page-Ready!")
  let user = wixUsers.currentUser; console.log("USER: ", user);
  user.getPricingPlans() 
  .then((pricingPlans)=> {console.log("Pricing-Plans: ", pricingPlans);
    let firstPlan = pricingPlans[0];  console.log("First-Plan: ", firstPlan);
    let  planName = firstPlan.name;   console.log("Plan-Name: ", planName);

    if (planName == '7 DAY FREE TRIAL $0'){console.log("Showing FREE-PLAN);
      $w('#text30, #text31').show();
      $w('#dropdown1, #emailInput, #button1').show();
      //searchForDuplicityFreePlan(); 
    }
    
    if(planName == 'BASIC'){console.log("Showing BASIC-PLAN);
      $w('#text30, #text31, #emailInput2, #button2').show();
      $w('#dropdown2, #dropdown3, #dropdown4').show();
      //searchForDuplicityBasicPlan();      
    }  


    // This Code-Part runs only when clicked onto submission-button...
    $w("#dataset1").onBeforeSave(async()=> {console.log("Submission-Button clicked, on beforeSave() for DATASET-1 (RegionSelectionQuizFree) running...");
      let checkEmailFree = await checkDatabase('RegionSelectionQuizFree', 'email', $w("#emailInput").value);
      console.log("Email-Check-Free-Result: ", checkEmailFree);
      let fieldCheck = $w("#dropdown1").value; console.log("Field-Check-Result: ", fieldCheck);

      if(checkEmailFree === false){console.log("FALSE running...");
        $w("#text32").text = "An error occurred. You have already submitted this form";
        return false     
      } else{console.log("ELSE-EmailCheck running... running...")}

      if(fieldCheck === ""){console.log("FALSE running...");
        $w("#text32").text = "An error occurred. Please select your region of interest";
        return false       
      } else{console.log("ELSE-FieldCheck running...")}
    });


    // This Code-Part runs only when clicked onto submission-button...
    $w("#dataset2").onBeforeSave(async() => {console.log("Submission-Button clicked, on beforeSave() for DATASET-2 (RegionSelectionQuizBasic) running...")
      let checkEmailBasic = await checkDatabase('RegionSelectionQuizBasic', 'email', $w("#emailInput2").value);
      console.log("Email-Check-Basic-Result: ", checkEmailBasic);
      let region1 = $w("#dropdown2").value, region2 = $w("#dropdown3").value, region3 = $w("#dropdown4").value;
      console.log("Region-1: ", region1);
      console.log("Region-2: ", region2);
      console.log("Region-3: ", region3);

      const regions = new Set(); console.log("Regions: ", regions);
      regions.add(region1);
      regions.add(region2);
      regions.add(region3);                
      regions.delete(""); 
      
      if(checkEmailBasic === false){
        $w("#text34").text = "An error occurred. You have already submitted this form";
        return false     
      } 

      if (regions.size !== 3) {
        $w("#text34").text = "An error occurred. Please select 3 different regions of interest";
        return false             
      }
    });
  });
});


function checkDatabase(collection, dbField, value) {console.log("Checking DATABASE...")
  wixData.query(collection)
  .eq(dbField, value)
  .find()
  .then((res)=>{console.log("RESULTS: ", res);
    if(res.items.length>0)  {return false} 
    else {return true}
  }).catch((err)=>{console.log(err);});
}

Please run that code and show what you get in console.
Also do not forget to OPEN THE 3-DOTS, so results can be investigated!
Show the results screenshot/screenshots.
Perhaps also show a related part of your DB to see the structure of your DB.