【问题标题】:I want to create a model for this JSON data in Loopback我想在 Loopback 中为这个 JSON 数据创建一个模型
【发布时间】:2019-04-16 07:22:14
【问题描述】:
 "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
}
},

【问题讨论】:

    标签: javascript node.js collections loopbackjs loopback


    【解决方案1】:

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

    假设您有 country 模型,则 address 模型将定义为:

    {
       "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'})
    

    【讨论】:

      猜你喜欢
      • 2015-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多