javascript - 我想在 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
}
},
解决方案
如果要在地址模型中使用相关模型,则需要使用关系。我建议使用 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'})
推荐阅读
- html - 为什么我的html页面顶部有边框
- ada - 如何将无界字符串转换为整数?
- c# - 如何列出在运行时使用 MakeGenericType 创建的程序集或命名空间中的类型?
- android - 如何使用 ArrayList 使用来自 firebase 的数据将多个数据添加到回收站
- php - 如何将 Worpress 的自动分页帖子限制为仅一种帖子类型?
- c# - Intellisense 不显示存储在外部文件中的 XML 注释
- angular - 角材质卡可点击
- http-headers - “添加过期标题” - HTML 呢?
- r - 从不同的数据框中获取唯一 ID
- android - 图像应该被缓存还是下载?什么是正确的方法?