火力点:如何获得一个参考键对象节点

问题描述:

// Creates local "temporary" object for holding employee data 
    var newTrain = { 
     tname: trainName, 
     dest: destination, 
     firstTime: firstTrainTime, 
     freq: frequency 
    }; 

    // Uploads train data to the database 
    trainDataBase.ref().push(newTrain); 

这是我弹“T弄清楚如何找我刚刚在服务器上创建的对象的关键我累之下,但它?回来不确定,也还累VAR =则newkey = trainDatabase.ref.push(newTrain).KEY但随后创建反对对一个,但我一键搞定火力点:如何获得一个参考键对象节点

// newKey = trainDataBase.ref(newTrain).key 
    // console.log("nodeKey" , newKey) 
    // Alert 
    console.log("train successfully added"); 

    // Clears all of the text-boxes 
    $("#trainName").val(""); 
    $("#destination").val(""); 
    $("#firstTrainTime").val(""); 
    $("#frequency").val(""); 

    // Prevents moving to new page 
    return false; 
    }); 

也许有更好的方式,但我已经用它来使它工作:

var trainDataBaseRef = trainDataBase.ref().push(); 
trainDataBaseRef.set({ 
    id: trainDataBaseRef.key, 
    // rest of object data 
}); 

走一个厕所处的K其docs额外的方式来做到这一点(Updating or deleting data部分):

function writeNewPost(...) { 
    var postData = { 
    // data 
    }; 

    // Get a key for a new Post. 
    var newPostKey = firebase.database().ref().child('posts').push().key; 

    // Write the new post's data simultaneously in the posts list and the user's post list. 
    var updates = {}; 
    updates['/posts/' + newPostKey] = postData; 
    updates['/user-posts/' + uid + '/' + newPostKey] = postData; 

    return firebase.database().ref().update(updates); 
} 
+0

尝试,但还没有得到上火力 – Nuno1895

+0

随机生成@ Nuno1895实际的关键:()调用'ref.push key'会给你一个新的推送ID(你称之为“随机密钥”)。然后,您可以使用'ref.child(key).set(....)'将值写入该键的位置。 @Omri:注意'ref.key()'用于2.x SDK,对于3.x,它已经更改为'ref.key'。 –

+0

@FrankvanPuffelen哦谢谢,编辑答案。非常感激。 –