firebase:如何获取对象节点的引用键

时间:2016-12-31 13:50:34

标签: javascript firebase firebase-realtime-database

// 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);

这是我可以的部分“我弄清楚如何获得我刚刚在服务器上创建的对象的密钥?我厌倦了下面但是它回来了未定义,也累了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;
    });

1 个答案:

答案 0 :(得分:3)

也许有更好的方法,但我已经用它来使其发挥作用:

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

请查看他们的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);
}