简体   繁体   中英

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 .

IE 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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM