【问题标题】:How are composite ids working in Loopback?复合 ID 如何在 Loopback 中工作?
【发布时间】:2018-11-04 04:28:12
【问题描述】:

我正在尝试使用MongoDB 实现具有Loopback 3.0.0 的复合ID。每对product_id/keyword 都应该是唯一的...

我查看官方文档:

https://loopback.io/doc/en/lb3/Model-definition-JSON-file.html#data-mapping-properties

这是我的模型:

{
  "name": "comparative",
  "plural": "comparative",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
     "validateUpsert": true
   },
  "properties": {
    "product_id": {
      "id": true,
      "type": "string",
      "required": true
    },
    "keyword": {
      "id": true,
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}

虽然,我所有尝试制作 product_id/keyword 的复合 ID 的尝试都失败了。

当我发帖时:

// 1st POST Success.
{
  "product_id": "string",
  "keyword": "string"
}
// 2nd POST Success.
{
  "product_id": "string1",
  "keyword": "string"
}
// 3rd POST FAILED -> I want it to success
{
  "product_id": "string",
  "keyword": "string1"
}

有什么想法吗?

即使在那之后,我也需要保留一个自动生成的 MongoDB id 来跟踪对象。

我尝试使用“idInjection”,但不使用复合 ID...(不生成任何东西...) 如果我添加另一个字段“id”并将生成设置为 true,则复合 id 根本不起作用(与之前部分起作用的情况相反)

谢谢,

【问题讨论】:

    标签: mongodb loopback


    【解决方案1】:

    你可以在product_idkeyword之间声明一个复合索引:

    https://loopback.io/doc/en/lb3/Model-definition-JSON-file.html#indexes

    {
      "name": "comparative",
      "plural": "comparative",
      "base": "PersistedModel",
      "idInjection": true,
      "options": {
         "validateUpsert": true
       },
      "properties": {
        "product_id": {
          "type": "string",
          "required": true
        },
        "keyword": {
          "type": "string",
          "required": true
        }
      },
      "validations": [],
      "relations": {},
      "acls": [],
      "methods": {},
      "indexes": {
        "productid_keyword_index": {
          "keys": {
            "product_id": 1, 
            "keyword": -1
          }, 
          "options": {
            "unique": true
          }
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      您不必在属性中输入id: true。如果您不想要默认标识,即仅对单个字段执行此操作。 _id 在 mongo 中

      "properties": {
          "product_id": {
            "type": "string",
            "required": true
          },
          "keyword": {
            "type": "string",
            "required": true
          }
        }
      

      我假设您有另一个模型产品,您希望将此模型与此模型相关联。为了实现这一点,添加关系

      查看this 环回文档以执行此操作。

      希望这有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-09
        • 2019-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多