Home > front end >  How to pass own unique key in firebase and update it as well without destroying the structure?
How to pass own unique key in firebase and update it as well without destroying the structure?

Time:02-12

I am currently trying to make a script where I pass my own unique key in firebase as primary key. It needs to work like this

StudentData
  -Student Unique id
    - referadID : "active",
    - referadID2 : "inactive",
    - referadID3 : "active",
  -Student Unique id2
    -referadIDnew : "active",

Here every student refers another student and once a refered student join that refered student who joined has his own unique id which stores value of active or inactive. The problem here is that if I use push it will generate a unique id which I don't want because it will make it difficult to work while using sorting. I don't want to do it. How can I create my own unique key in studentUniqueid2. I tried using transaction instead of push but the issue is that transaction instead of adding another key value pair would simply update the whole key leaving only the latest student unique id in the table which I don't want. Here is my code

let createData=adminDatabase.ref('/ReferralSystem/joinedtransactionlog');
createData.transaction(function(currentData){

  if(currentData !== InviterId){
    return {
      [InviterId]: {
        [member.id] : "active" 
      }
    }
  }else{
    console.log("curretn data exists");
  }
});

I am using javascript and working on firebase realtime database system with platform of Admin.

CodePudding user response:

If I understand correctly, you have two UIDs: one for the inviter and the other for the invitee/member. In that case, you can write the structure in your question with:

createData.child(inviterUID).child(memberUID).set("active");

Doing this with a simple set operation will scale much better than the transaction you tried, since you're creating contention on the entire StudentData node while this merely performs an idempotent write.

There is no need to prevent writing the data if it already exists, as the operation is idempotent: subsequent writes don't change the result of the first write.

  • Related