Auzy
Auzy

Reputation: 2155

Get Firebase Object data based on ID in another ref

I have this broken CodePen that I am attempting to get the info of an object in another Firebase Ref based on the objects .key or id...

I have to Firebase Refs: The content

[
  {
    "name": "objecta",
    ".key": "objecta"
  },
  {
    "name": "objectb",
    ".key": "objectb"
  },
  {
    "name": "objectc",
    ".key": "objectc"
  }
]

and the Related that lists the object by key and then the key of the ones that are related to that item.

[
  {
    "objectc": true,
    ".key": "objectb"
  }
]

I am trying to use the following code to go through the relatedRef by key:

var theKey = "objectb"

function getDiscoverBarContent(key, cb) {
    relatedRef.child(key).on("child_added", snap => {
        let relateRef = relatedRef.child(snap.key);
        relateRef.once("value", cb);
        console.log('relate:' + relateRef)
    });
}

then get the data of the object that it's related to and log it to the console:

getDiscoverBarContent(theKey, snap => {
    var snapVal = snap.val();
    console.log(snapVal)
}); 

Currently it is returning null when I need it to return the object info in contentRef referenced in the relatedRef...any ideas?

Upvotes: 1

Views: 670

Answers (1)

Auzy
Auzy

Reputation: 2155

I was referencing the wrong ref in the JS function. Everything was right except this:

var theKey = "objectb"

function getDiscoverBarContent(key, cb) {
    relatedRef.child(key).on("child_added", snap => {
        //This should have referenced the contentRef:
        let relateRef = relatedRef.child(snap.key); 
        //like so
        let relateRef = contentRef.child(snap.key);
        relateRef.once("value", cb);
        console.log('relate:' + relateRef)
    });
}

Upvotes: 1

Related Questions