Jason
Jason

Reputation: 1977

Accessing an included object

I have the following JSON Object, which is the result of a loopback model (Classifications), with a relationship with another model (Labels).

My call to get the classifications is:

modClassification.findOne({ 
             where: { id: classificationid }, 
             include: 'labels' }, 
             function( err, classification ){ ...

And this returns classification with something like

{ id: 'b01',
  title: 'population',
  country_id: 1,
  labels: 
   [ { column_id: 'b1',
       classification_id: 'b01',
       classification_title: 'population',
       dsporder: 1,
       label: 'Total_Persons_Males',
       country_id: 1,
       id: 1 },
     { column_id: 'b2',
       classification_id: 'b01',
       classification_title: 'population',
       dsporder: 2,
       label: 'Total_Persons_Females',
       country_id: 1,
       id: 2 } ] }

which is what I would expect.

I now need to loop over the labels and access it's properties, but this is where I am stuck.

classification.labels[0] = undefined..

I have tried looping, each and whatever I can find online, but can't seem to get to each labels properties.

Can someone tell me what I am doing wrong/need to do?

Thanks

Upvotes: 0

Views: 53

Answers (1)

notbrain
notbrain

Reputation: 3396

When you are including related models inside a findOne call, you need to JSONify the result before accessing the related records:

classification = classification.toJSON()

Then you should be able to access the included label items as you expect.

See https://docs.strongloop.com/display/public/LB/Include+filter, specifically the "Access included objects" section.

Note this does not work the same when you retrieve more than one result in an array. In that case you'll need to perform toJSON() on each item in the array.

Upvotes: 1

Related Questions