loopback model json数组对象严格过滤

时间:2017-10-24 10:41:20

标签: node.js mongodb loopbackjs strongloop

我使用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中的属性,此不起作用

即。如果您将此对象发布到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自己验证嵌套文档?

1 个答案:

答案 0 :(得分: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模型

相关问题