Search code examples
node.jsmongodbloopbackjsstrongloop

loopback model json array of objects strict filter


I'm using strongloop loopback v3 REST API with mongoDB as datasource. My model order.json is

{
  "name": "order",
  "base": "PersistedModel",
  "strict": true,
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "orderNo": {
      "type": "string"
    },
    "lines": {
      "type": [
        {
          "type": {
            "description": "string",
            "quantity": "number"
          }
        }
      ]
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}

I set "strict": true so that the model accepts only predefined properties. But this does not work for properties in the array lines.

I.E. if you post this object to the API you get an ValidationError (Code 422) as expected:

{
  "orderNo": "xyz",
  "someOtherProp": "hello",
  "lines": [
    {
      "description": "abc",
      "quantity": 5
    }
  ]
}

But if you post this JSON object loopback saves the object to mongoDB

{
  "orderNo": "xyz",
  "lines": [
    {
      "description": "abc",
      "quantity": 5,
      "someOtherProp": "hello"
    }
  ]
}

My question is about if there are any flags to be set in the model JSON to validate an array of objects? Or do I have to validate the nested documents by my own via the order.js model extension file?


Solution

  • define the lines as another model and make it relation with type embedsMany in order model.

    lines model

    {
        "name": "line",
        "base": "Model",
        "strict": true,
        "idInjection": true,
        "properties": {
          "description": {
            "type": "string"
          },
         "quantity":{
           "type":"number"
          }
      }
    }
    

    order model

    {
        "name": "order",
        "base": "PersistedModel",
        "strict": true,
        "idInjection": true,
        "options": {
          "validateUpsert": true
        },
        "properties": {
          "orderNo": {
            "type": "string"
          }
        },
        "validations": [],
        "relations": {
           "lines":{
            "type": "embedsMany",
            "model": "line",
            "property": "lines"
           }
        },
        "acls": [],
        "methods": {}
    }
    

    this way loopback will validate line model