【问题标题】:loopback model json array of objects strict filter环回模型 json 对象数组 严格过滤
【发布时间】:2018-03-01 03:38:16
【问题描述】:

我使用 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 对象,loopback 会将对象保存到 mongoDB

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

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

【问题讨论】:

标签: node.js mongodb loopbackjs strongloop


【解决方案1】:

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

线条模型

{
    "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模型

【讨论】:

  • 绝对正确。我忽略了这个网站:Embedded models and relations。但请确保在嵌入定义中使用'base: "Model"'。
  • 是的,你是对的@LonelyIsland 我会编辑答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 2019-12-02
  • 2019-10-07
  • 2021-08-28
  • 1970-01-01
  • 2018-01-24
  • 1970-01-01
相关资源
最近更新 更多