Nuno1895
Nuno1895

Reputation: 45

firebase: How to get a reference key for an object node

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

Upvotes: 2

Views: 3862

Answers (1)

Omri Aharon
Omri Aharon

Reputation: 17064

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

Upvotes: 4

Related Questions