Nested (embedded) tree model in loopback with mongodb

I'm trying to figure out how to set a very simple nested "treenode" model in a loopback with mongodb. The idea is that there will only be one model (for this): a treenode, which can contain other treenodes. I would like to save them immediately via nested mongodb 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: []       
      },  
  ]

      

Also, every node at any level has a relationship to other models.

There will be many top level root treenodes (docs). What type of relationship and how should I use for this?

+3


source to share


2 answers


Unfortunately, there is still little documentation on this topic. For now see http://docs.strongloop.com/display/LB/Embedded+models+and+relations



+1


source


You must define nested models separately and then declare them as transient models. Then the loopback should store them in its parent model as described http://loopback.io/doc/en/lb2/Embedded-models-and-relations.html#transient-versus-persistent-for-the-embedded-model

Define 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 something like this:

generic / model / NestedNode.json

{
  "name": "NestedNode",
  "base": "Model",
  "properties": {
      "name": {
          "type": "string"
      }
  },
  "relations": {
    "nodes": {
      "type": "referencesMany",
      "model": "NestedNode",
      "options": {
        "validate": true,
        "forceId": false
      }
    }
}

      

generic / model / BaseNode.json

{
  "name": "BaseNode",
  "base": "PersistedModel",
  "properties": {
     "name": {
        "type": "string"
     }
  },
  ...
  "relations": {
    "nestedNode": {
      "type": "embedsMany",
      "model": "Link",
      "scope": {
        "include": "linked"
      }
    }
  },
  ...
}

      

You may also have problems with curcular reference.

0


source







All Articles