简体   繁体   中英

Firebase - Push to pushed data

Here's my data

{
  "deck" : {
    "-JkpwAnieKjQVsdtPD4m" : {
      "deck" : "Deck 1",
      "user" : "simplelogin:1"
    },
    "-Jkq4unexm-qwhO_U2YO" : {
      "deck" : "Deck 2",
      "user" : "simplelogin:1"
    },
    "-Jkq5-II1q5yM6w3ytmG" : {
      "deck" : "Deck 3",
      "user" : "simplelogin:6"
    },
    "-Jks5mbMHmPB9MwnnOCj" : {
      "deck" : "Deck 4",
      "user" : "simplelogin:1"
    }
  }
}

If I want to add:

      cards: {
        "-GeneratedKey":{
          "title":"foo",
          "text":"bar",
        }
      }

to say the item with the deck "Deck 2", how do I select that object to push to it. The end result would be:

{
  "deck" : {
    "-JkpwAnieKjQVsdtPD4m" : {
      "deck" : "Deck 1",
      "user" : "simplelogin:1"
    },
    "-Jkq4unexm-qwhO_U2YO" : {
      cards: {
        "-GeneratedKey":{
          "title":"foo",
          "text":"bar",
        }
      }
      "deck" : "Deck 2",
      "user" : "simplelogin:1"
    },
    "-Jkq5-II1q5yM6w3ytmG" : {
      "deck" : "Deck 3",
      "user" : "simplelogin:6"
    },
    "-Jks5mbMHmPB9MwnnOCj" : {
      "deck" : "Deck 4",
      "user" : "simplelogin:1"
    }
  }
}

Here is what I tried:

  deckRef.orderByChild('deckName').equalTo('Deck 2').push({
    card: {
      title: 'foo',
      text: 'bar'
    }
  });

but that just returned an error. What do I do to achieve this?

deckRef.orderByChild('deckName').equalTo('Deck 2') returns a query, not a ref. A query can match many nodes. Even though in your case it only matches one, you will need to first capture that one node into a ref to be able to push to it.

var query = deckRef.orderByChild('deckName').equalTo('Deck 2');
query.once('child_added', function(snapshot) {
    snapshot.ref().child('cards').push({
        title: 'foo',
        text: 'bar'
    });
});

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