Reputation: 1712
I try to figure out how to set a very simple nested "treenode" model in loopback with mongodb. The idea is there will be only one model (for this): treenode which can contain other treenodes. I would like to store them at once via mongodb nested documents:
- TreeNode (document):
Name: "A",
Nodes: [
{
Name: "A-A",
Nodes: [
{
Name: "A-A-A",
Nodes: []
},
{
Name: "A-A-B",
Nodes: []
},
{
Name: "A-A-C",
Nodes: []
}
},
{
Name: "A-B",
Nodes: []
},
]
Additionally each node at any level has relations to other models.
There will be many top-level root treenodes (documents). Which relation type and how should I use for this?
Upvotes: 3
Views: 3172
Reputation: 1277
You should define the nested models separately and then declare them as transient models. Then loopback should store them in its parent model, as explained http://loopback.io/doc/en/lb2/Embedded-models-and-relations.html#transient-versus-persistent-for-the-embedded-model
Define a transient data source
server/datasources.json
{
...
"transient": {
"name": "transient",
"connector": "transient"
}
}
server/model-config.json
{
...
"BaseNode": {
"dataSource": "db",
"public": true
},
"NestedNode": {
"dataSource": "transient",
"public": false
}
}
And the model definitions should be somthing like this:
common/models/NestedNode.json
{
"name": "NestedNode",
"base": "Model",
"properties": {
"name": {
"type": "string"
}
},
"relations": {
"nodes": {
"type": "referencesMany",
"model": "NestedNode",
"options": {
"validate": true,
"forceId": false
}
}
}
common/models/BaseNode.json
{
"name": "BaseNode",
"base": "PersistedModel",
"properties": {
"name": {
"type": "string"
}
},
...
"relations": {
"nestedNode": {
"type": "embedsMany",
"model": "Link",
"scope": {
"include": "linked"
}
}
},
...
}
You also may experience curcular reference problems.
Upvotes: 0
Reputation: 2781
Unfortunately, there isn't much documentation on this topic yet. For now, see http://docs.strongloop.com/display/LB/Embedded+models+and+relations
Upvotes: 1