3

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?

2 Answers 2

1

Unfortunately, there isn't much documentation on this topic yet. For now, see http://docs.strongloop.com/display/LB/Embedded+models+and+relations

Sign up to request clarification or add additional context in comments.

1 Comment

Link only answers are not enough, because they will be useless when the linked content goes down. Please add the relevant parts into your answer and explain how that solves the problem.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.