这是我第一次处理NoSQL形式的数据库,我对面向文档的数据库中的“关系”有点困惑。我使用的是LoopBack & AngularJS。
我有一个has many
page
as it's children
的模型(即菜单项和子菜单)。
page
模型如下:
"properties": {
"name": {
"type": "string",
"required": true
},
"slug": {
"type": "string"
},
"link": {
"type": "string"
},
"createdAt": {
"type": "date",
"required": true
},
"children": {
"type": [
"object"
]
}
},
使用
"relations": {
"children": {
"type": "hasMany",
"model": "page",
"foreignKey": "parentId"
}
},
我的困惑是,每当我对LoopBack应用程序接口执行explore
操作,然后对parent
页面执行get
操作时,我都看不到填充的children
属性。但是,执行一个get
来查看父级的孩子(使用父级的id
)结果很好--我可以看到用它的父级填充的parentId
。
我的问题是,在处理NoSQL/面向文档的数据库时,这是正常的,还是我做错了什么?
非常感谢!
发布于 2016-11-27 00:56:54
我相信你可能错过了这段关系的另一个方向。
您可以在子项中执行belongsTo relation,以指定它属于父项。
这应该能让你在浏览器中看到两个方向的方法。
此外,foreingKey parentId
应该设置在子对象上,而不是父对象上。例如,在父relations
定义上保留foreignKey为空,而在children
关系定义上使用它。
因此,一方面,在模型中,您将在关系字段中拥有:
"children": {
"type": "hasMany",
"model": "page",
"foreignKey": ""
},
而且还
"parent": {
"type": "belongsTo",
"model": "page",
"foreignKey": "parentId"
},
再加上你的任何其他关系。
我已经对此进行了测试,它是有效的,尽管我对关系使用了两个不同的模型,而不是只使用一个模型。
即,我使用
ModelA hasMany ModelB
和ModelB belongsTo ModelA
而不是
ModelA hasMany ModelA
和ModelA belongsTo ModelA
发布于 2016-11-23 03:22:50
在mongoose中,当您想要填充页面的“子元素”时,您需要使用以下命令明确地请求它:
Pages.find({})
.populate('children')
.exec(function(err, pages){
//..
})
在LoopBack的页面(http://loopback.io/doc/en/lb2/Querying-related-models.html)上有一个类似的叫做"include“的东西,你应该试着这样做:
Page.find({include:'children'}, function() {
//...
});
如果有效,请让我知道!
https://stackoverflow.com/questions/40749760
复制相似问题