0

I've currently built an API using Loopback based on an existing DB and schema from an older API. Everything works very well with the exception of 'populate' or related models.

I would like to be able to query related models in the loopback way, like so

User.find({include: 'test'}, function() { /* ... */ });

i've added the relations in the JSON files

"relations": {
    "test": {
        "type": "hasOne",
        "model": "Address",
        "foreignKey": "addressId"
    }
}

however I can't seem to get anything to be returned - although I can see the additional properties in the explorer.

So, my question is, can related models be set-up over existing data or does it have to be populated as the data is created?

EDIT: my connector is mongo

sidonaldson
  • 24,431
  • 10
  • 56
  • 61
  • 1
    It can be set up with the existing data. What's the schema of the tables? Also in your example, your relation name is `test`, so you have to `include` with that name: `User.find({ include: 'test' })` – Farid Nouri Neshat Jun 13 '17 at 10:56
  • 1
    For more debugging you can see the loopback queries, if you set the `DEBUG` environment variable with `loopback:*` – Farid Nouri Neshat Jun 13 '17 at 10:57
  • Thanks @FaridNouriNeshat an oversight pasting code, have updated the ticket. Regarding setting up with existing data is there a link you know of? I've edited the question to state i'm using the mongo connector. – sidonaldson Jun 13 '17 at 11:53
  • 1
    You can use [`instance introspection`](https://loopback.io/doc/en/lb2/Creating-models-from-unstructured-data.html) to create the models but it won't have the relationships set up. Can you share valid examples of data from both collections? – Farid Nouri Neshat Jun 13 '17 at 13:04
  • @FaridNouriNeshat thank you for your help. Turns out it was quite simple after all and i just didn't understand how to set-up the foreign keys – sidonaldson Jun 15 '17 at 14:31

1 Answers1

0

I found the answer on another SO quesiton: Loopback-relationship-on-non-id-field

It turns out the foreignKey needs to be the same for hasMany and belongsTo

sidonaldson
  • 24,431
  • 10
  • 56
  • 61