How to do CRUD operations in Firebase with CurrentUserId?

可紊 提交于 2019-12-12 01:09:47

问题


I'm creating a simple website and i'cant use firebase realtime databases crud operations with currentUserId.

My auth system working good; i can signIn/signUp/signOut on database. And i can write data to firebase with getting inputs from form.

    //GETTING DATA WITH FORM
    
    // Listen for form submit
    document.getElementById('form').addEventListener('submit', submitForm);
    
    
    // Submit form
    function submitForm(e){
      e.preventDefault();
    
      // Get values
      var name = getInputVal('name');
      var sets = getInputVal('sets');
      var reps = getInputVal('reps');
      var weights = getInputVal('weights');
      
      // Write data
      writeData(name, sets, reps, weights);
    
      // Clear form
      document.getElementById('form').reset();
    }
    
    
    // Function to get form values
    function getInputVal(id){
      return document.getElementById(id).value;
    }
    
    
    //CRUD OPERATIONS
    
    // Reference
    var DataRef = firebase.database().ref('users/'  + 'exercises/');
    
    // Write data to database
    function writeData(name, sets, reps, weights){
      var newDataRef = DataRef.push();
      newDataRef.set({
    
        name: name,
        sets: sets,
        reps: reps,
        weights: weights,
        
      });
    }

I didn't want to start reading, updating and deleting until I solved this id problem.

So how to do CRUD operations with each users with id? What can i do?


回答1:


Are you asking how to write data in a location that is specific to the current user? If so:

var currentUser = firebase.auth().currentUser;
var DataRef = firebase.database().ref('users/' + currentUser.uid + '/exercises/');

Note that this only works if the current user is guaranteed to be already signed in. If you can't guarantee that, put the above code in an auth state listener.



来源:https://stackoverflow.com/questions/53868286/how-to-do-crud-operations-in-firebase-with-currentuserid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!