"US Virgin Islands": [
"Charlotte Amalie",
"Christiansted",
"Frederiksted",
"Kingshill",
"St John Island"
],
我有这个 JSON 文件。我想按原样保存数据。所以国家名称和它拥有的所有城市。我创建了一个名为地址的集合,但我不知道如何正确设置属性。我使用 MongoDB 作为数据库。我想创建 json 模型。
"name": "address",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"country": {
"type": "object",
"required": true
}
},
最佳答案
如果您想在地址模型中使用相关模型,则需要使用关系。我建议使用 Loopback cli 来完成此操作。另外,检查relations环回文档中的章节以获取有关关系的更多信息。
假设您有国家/地区模型,地址模型将定义为:
{
"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'})
关于javascript - 我想在 Loopback 中为此 JSON 数据创建一个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53281358/