首页 > 解决方案 > 我想在 Loopback 中为这个 JSON 数据创建一个模型

问题描述

 "US Virgin Islands": [
"Charlotte Amalie",
"Christiansted",
"Frederiksted",
"Kingshill",
"St John Island"
],

我有这个 JSON 文件。我想按原样保存数据。所以国家名称和它拥有的所有城市。我创建了一个名为 address 的集合,但我不知道如何正确设置属性。我正在使用 MongoDB 作为数据库。我想创建 json 模型。

 "name": "address",
  "base": "PersistedModel",

  "idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
 "country": {
   "type": "object",
   "required": true
}
},

标签: javascriptnode.jscollectionsloopbackjsloopback

解决方案


如果要在地址模型中使用相关模型,则需要使用关系。我建议使用 loopback cli 来执行此操作。此外,请查看环回文档中的关系章节以获取有关关系的更多信息。

假设您有国家模型,地址模型将定义为:

{
   "name":"address",
   "base":"PersistedModel",
   "idInjection":true,
   "options":{
      "validateUpsert":true
   },
   "relation": {
      "country": {
         "type": "hasOne",
         "model": "country"
         "foreignKey": ""
      }
   }
}

此外,您需要在地址模型中创建一个 belongsTo 关系:

{
   "name":"country",
   "base":"PersistedModel",
   "idInjection":true,
   "options":{
      "validateUpsert":true
   },
   "properties": { ... }
   "relation": {
      "address": {
         "type": "belongsTo",
         "model": "address"
         "foreignKey": ""
      }
   }
}

它将自动countryId在您的地址模型中创建一个字段。然后,如果您想使用整个国家模型实例而不是仅加载地址,则countryId需要调用以下内容:

Address.find({where: {id: someId}, include: 'country'})

推荐阅读