2016-11-08 70 views
1

我有簡單文檔分段帶有一個屬性名稱。每個細分受衆羣都可以有0..N個孩子,並且他們的孩子也可以有細分孩子0..N,所以基本的樹結構。
邊緣從子段創建到父級。OrientDB:如何在NodeJS中以樹結構模型獲取所有文檔及其子項(具有所有屬性)

我需要的是在的NodeJS根鏈段與所有的孩子和孫子等在一個命令來獲取,這樣我就可以找回這樣的事情:

[ 
     { 
     "@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" 
       } 
      ] 
      } 
     ] 
     } 
    ] 

回答

0
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();}); 
0

試試這個:

var OrientDB = require('orientjs'); 
var db = OrientDB({ 
    host: 'localhost', 
    port: 2424, 
}); 
var db = db.use({ 
    name: 'your db name', 
    username: 'your username', 
    password: 'your password' 
}); 
db.query('traverse * from Segment') 
.then(function (response) { 
console.log(response); 
}); 
db.close(); 

希望它可以幫助

問候

+0

thx對你有幫助,但是隻能遍歷返回'rid'。我需要使用fetchplan來檢索段名稱。 –

相關問題