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

THIS IS THE PART I CAN"T figure out how do I get a key for the object I just created on the server? I tired the below but it comes back undefined, also also tired var = newKey = trainDatabase.ref.push(newTrain).key but then it creates to object versus one but I do get a 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;
    });
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Nuno1895
  • 45
  • 1
  • 4

1 Answers1

4

Perhaps there's a better way, but I've used this to make it work:

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

Take a look at their docs for an additional way to do this (Updating or deleting data section):

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);
}
Omri Aharon
  • 16,959
  • 5
  • 40
  • 58
  • tried that also but not getting the actual key that generates randomly on firebase – Nuno1895 Dec 31 '16 at 15:58
  • @Nuno1895: calling `ref.push().key` will give you a new push id (what you call "random key"). You can then use `ref.child(key).set(....)` to write a value to a location at that key. @Omri: note that `ref.key()` is for the 2.x SDK, for 3.x it has been changed to `ref.key`. – Frank van Puffelen Dec 31 '16 at 16:27
  • @FrankvanPuffelen Oh thanks, edited answer. Much appreciated. – Omri Aharon Dec 31 '16 at 16:46