loopback model json数组对象严格过滤

问题描述 投票:0回答:1

我正在使用strongloop loopback v3 REST API和mongoDB作为数据源。我的模型order.json

{
  "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": {}
}

我设置"strict": true使the model accepts only predefined properties。但这不适用于数组lines中的属性。

I.E.如果您将此对象发布到API,则会出现预期的ValidationError(代码422):

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

但是如果你发布这个JSON对象,则回送将对象保存到mongoDB

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

我的问题是关于是否在模型JSON中设置任何标志以验证对象数组?或者我必须通过order.js model extension file验证我自己的嵌套文档?

node.js mongodb loopbackjs strongloop
1个回答
1
投票

lines定义为另一个模型,并使其与embedsMany模型中的order类型相关联。

线模型

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

订单模型

{
    "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": {}
}

这样环回将验证line模型

© www.soinside.com 2019 - 2024. All rights reserved.