簡體   English   中英

我想在Loopback中為此JSON數據創建模型

[英]I want to create a model for this JSON data in Loopback

 "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
}
},

如果要在地址模型中使用相關模型,則需要使用關系。 我建議使用環回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'})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM