Search code examples
mongodbloopbackjs

Loopback relations not populating array of Object IDs


I have 2 models so far: workflow-core,workflow-step'

Workflow core has a steps property that is of type array and contains 1-many steps. When calling get on workflow-core the response body is not populating the steps array with the actual step objects.

workflow-core.json:

{
"name": "workflow-core",
"base": "PersistedModel",
"idInjection": true,
"options": {
  "validateUpsert": true
},
"injectOptionsFromRemoteContext": true,
"properties": {
  "name": {
    "type": "string",
    "required": true,
    "default": "Untitled"
  },
  "user_id": {
    "type": "string",
    "required": false
  },
  "steps": {
    "type": "array",
    "required": false,
    "default": []
  }
},
"validations": [],
"relations": {
  "steps": {
    "model": "workflow-step",
    "type": "embedsMany"
  }
},
"acls": [
  {
    "accessType": "*",
    "principalType": "ROLE",
    "principalId": "$unauthenticated",
    "permission": "DENY"
  }
],
"methods": {}
}

workflow-step.json:

{
"name": "workflow-step",
"base": "PersistedModel",
"idInjection": true,
"options": {
  "validateUpsert": true
},
"properties": {
  "name": {
    "type": "string",
    "required": true,
    "default": "Untitled Step"
  },
  "status": {
    "type": "string",
    "default": "waiting"
  }
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}

What the Loopback Explorer says I should get (and what I want):

{
  "name": "Untitled",
  "user_id": "string",
  "steps": [],
  "id": "string",
  "workflow-steps": [
    {
      "name": "Untitled Step",
      "status": "waiting",
      "id": "string"
    }
  ]
}

What I am getting:

{
    "name": "Updated with step",
    "user_id": "231569461654",
    "id": "5b75bc769b3143103cb787c2",
    "workflow-steps": [],
    "steps": [
      "5b760fff24ccc23934fef240"
    ]
  }

hasMany seems to do the same thing except there is no workflow-steps array property in the response body


Solution

  • This ended up being an easy fix:

    1. I changed the step relation in workflow-core.json:

      "relations": {
          "steps": {
             "type": "hasMany",  <-- used hasMany instead of embedsMany
             "model": "WorkflowStep",
             "foreignKey": ""
           }
      },
      
    2. When using the api explorer window, I needed to add the filter: {"include": "steps"}

    enter image description here

    Not sure if this was part of it but I changed my model names as follows:

    workflow-core ---> WorkflowCore
    workflow-step ---> WorkflowStep