简体   繁体   中英

Using Firebase Push key as Key in Second Push

I'm trying to add two related items to my Firebase database. I want to push one item, then get that item's newly created key and use it as the key for the second item in a different tree. I've tried querying the database to get the last key created and using it as the key for the second push, but it's still just generating a new key for it. Here's the code that I'm using:

save: function() {
    if (this.$.document.isNew && (this.editableCard.title || this.editableCard.body)) {
        return this.$.document.save(this.cardsPath).then(function() {
            this.$.document.reset();
            var sceneRef = firebase.database().ref().child(this.cardsPath);
            var scene = sceneRef.orderByKey().limitToLast(1);
            var sceneKey = scene.key;
            this.$.document.save('/documents/', sceneKey);
        }.bind(this));
    }
    return Promise.resolve();
}

(I'm using Polymer, and my starting point is the note-app demo for Polymerfire).

Any ideas on how I can retrieve the new key of the first push and use it for the second push? Thanks!

EDIT

I found the answer in Firebase's documentation for Reading and Writing to the database for Web. Link

push() returns a DatabaseReference immediately. You can ask that reference what its key is, using getKey() , then use that string to update another location in your database.

You can access the key property on the original database reference and use that as the key for the second one, like so:

let firstObjRef = firebase.database().ref('/first/path/).push(firstObj, (error) => {
  videoObj["roomUploadedTo"] = this.roomName;
  var updateObj = {};
  updateObj[videoObjRef.key] = videoObj;

  firebase.database().ref('/second/path/').update(updateObj).then( (e) => {
    console.log('update went through. booyah! ' + e);
  })

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