orientdborientjs

OrientDB: How to fetch all documents and their children (with all properties) in a tree structure model in NodeJS


I have simple document Segment with one property name. Every segment can have 0..N children of type Segment and their children can also have Segment children 0..N, so basic tree structure.
Edges are created from child Segment to parent.

What I need is to fetch in NodeJS root Segements with their all children and grandchildren and so on in one command, so I can retrieve something like this:

    [
      {
        "@rid": "#1:1",
        "name": "Segment 1",
        "segments": [
          {
            "@rid": "#1:2",
            "name": "Segment 1.1",
            "segments": [
              {
                "@rid": "#1:3",
                "name": "Segment 1.1.1"
              },
              {
                "@rid": "#1:4",
                "name": "Segment 1.1.2"
              }
            ]
          },
          {
            "@rid": "#1:5",
            "name": "Segment 1.2",
            "segments": [
              {
                "@rid": "#1:6",
                "name": "Segment 1.2.1"
              },
              {
                "@rid": "#1:7",
                "name": "Segment 1.2.2"
              } 
            ]
          }
        ]
      },
      {
        "@rid": "#1:8",
        "name": "Segment 2",
        "segments": [
          {
            "@rid": "#1:9",
            "name": "Segment 2.1",
            "segments": [
              {
                "@rid": "#1:10",
                "name": "Segment 2.1.1"
              },
              {
                "@rid": "#1:11",
                "name": "Segment 2.1.2"
              }
            ]
          },
          {
            "@rid": "#1:12",
            "name": "Segment 2.2",
            "segments": [
              {
                "@rid": "#1:13",
                "name": "Segment 2.2.1"
              },
              {
                "@rid": "#1:14",
                "name": "Segment 2.2.2"
              } 
            ]
          }
        ]
      }
    ]

Solution

  • function parseSegment(segment) {
        var parsedSegment = {
            id : segment['@rid'].toString(),
            name: segment.name
        };
    
        if (segment.in_) {
            var children = segment.in_.all().map(edge => parseSegment(edge.out));
    
            if (children.length) {
                parsedSegment.children = children;
            }
        }
    
        return parsedSegment;
    }
    
    db.select()
        .from('Segment')
        .where('out().size() = 0')
        .fetch({'in_':'-1'})
        .transform(parseSegment)
        .all()
        .then(segments => {
            console.log(JSON.stringify(segments, null, 2));
        })
        .finally(() => {db.close();});