Search code examples
node.jsentity-relationshiploopbackjsapi-designstrongloop

Loopback relation never return values


I recently started working with LoopBack to build our own API. It's based on a Mongo DB (pretty new to me too). I tried to configured multiple relations (I tried different types) and I never get result in the response. It seems to be properly configured as if I check the Explorer, I see the relation in the example value.

For instance, I have companies, related to one companyGroup as:

- Company" Belongsto CompanyGroup
- CompanyGroup hasMany Company

Here is my relation configured in my models

In Company.json

"relations": {
    "companyGroup": {
      "type": "embedsOne",
      "model": "companyGroup",
      "foreignKey": "groupId",
      "primaryKey": "",
      "property": "group"
    }
  },

In company-group.json

"relations": {
    "companies": {
      "type": "hasMany",
      "model": "company",
      "foreignKey": "groupId",
      "options": {
        "nestRemoting": false
      }
    }
  },

If I check the Explorer, I see the relation configured in the example value :

[
  {
    "id": "string",
    "name": "string",
    "groupId": "string",
    "logo": "string",
    "isGroupManager": true,
    "createdAt": "$now",
    "updatedAt": "$now",
    "group": {
      "name": "string",
      "createdAt": "2018-03-08T14:38:51.155Z",
      "id": "string"
    }
  }
]

But any response will miss the company group part:

{
"id": "5a9ea3fc6d48a58bb619d180",
"name": "Agency (BXL)",
"groupId": "5a9ea3fc6d48a58bb619d17f",
"createdAt": "2018-03-06T14:21:48.322Z",
"updatedAt": "2018-03-06T14:21:48.322Z"

},

What did I configured wrong ? Where should I look ? I have an recent updated version of loopback Thanks !

Laurent


Solution

  • If you are getting group Id in your response and want the group instance in the response too, you can use an include filter.

    https://loopback.io/doc/en/lb3/Include-filter.html

    in your case, you can use a GET like request like the following

    /api/companies/{comp_id}?filter={"include":{"group":true}}
    
    /api/companies/{comp_id}?filter={"include":["group"]}
    
    /api/companies?filter[include]=group