简体   繁体   中英

How to add to use push() with a specified key instead of default key on firebase

Firebase上的实时数据库屏幕截图

So I'm trying to store user information in a database using Firebase, which includes their email, ID, and associated group.

Each time a new user creates an account their data is saved in the parent node Managers

Here is my code so far,

var manRef = firebase.database().ref('Managers');

function saveManage(sEmail, uid, society){

manRef.push({ ManagerID : uid, Email : sEmail, Society : society }) }

For variables in the function saveManage are gathered from entries on a form, I want to be able to push a new entry into the node Managers but have the highlighted key in the image be set as a predefined value, such as the uid so that it is easier for me to reference the individual entries later

It sounds like you just want to set() the value at your predefined location instead of using push(), which always uses its own algorithm for generating the key.

manRef.child(uid).set({
        ManagerID : uid,
        Email : sEmail,
        Society : society
    })
}

I would do something like below to make this function robust. Note, I like to .toLowerCase() properties before storing them. This way you can now call this same function even if you want to update only their email and leave the rest alone.

var managersRef =  firebase.database().ref('managers');

function saveManager(email, uid, society){
    var obj = {};
    if (uid !== undefined){
      if (email !== undefined){
        obj["email"][email.toLowerCase()];
      }
      if (society !== undefined){
        obj["society"][society.toLowerCase()];
      }
      managersref.child(uid).update(obj);
    } else {
      console.log("uid required") //or throw an error
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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