Search code examples
node.jsrestloopbackjs

loopback 3 manage embedsMany over REST api


I have one loopback model pack

{
  "name": "pack",
  "plural": "packs",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "name": {
      "type": "string",
      "required": true
    },
    "description1": {
      "type": "string"
    },
    "description2": {
      "type": "string"
    }
  },
  "validations": [],
  "relations": {
    "products": {
      "type": "embedsMany",
      "model": "packProduct",
      "property": "products",
      "options": {
        "validate": true,
        "forceId": false
      }
    }
  },
  "acls": [
    {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "$unauthenticated",
      "permission": "DENY"
    }
  ],
  "methods": {},
  "strict": true
}

Now the packProduct model

{
  "name": "packProduct",
  "plural": "packProducts",
  "base": "Model",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "productId": {
      "type": "string",
      "required": true
    },
    "price": {
      "type": "number",
      "required": true
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {},
  "strict": true
}

When I am sending a POST request to create a pack with only a name it works but if I am sending

{ name: "test", products: [] }

I have The pack instance is not valid. Details: products is not defined in the model (value: undefined).


Solution

  • I was missing this part of the configuration https://loopback.io/doc/en/lb3/Embedded-models-and-relations.html#transient-versus-persistent-for-the-embedded-model

    Needs to add in model-config.json

    "packProduct": {
        "dataSource": "transient",
        "public": false
    }
    

    And in datasources.json

    "transient": {
        "name": "transient",
        "connector": "transient"
    }