2017-01-26 4 views
0

ノードを使用してmongoDBでカテゴリを作成しました。すべての挿入に親プロパティを追加して親カテゴリを決定しました。hongarchyでmongodbに追加されたカテゴリとサブカテゴリからjsonオブジェクトを作成

[{ _id: 5889a06f274afdfd6f2bf249, 
    cat_id: 1, 
    title: 'Parent Category', 
    description: '', 
    parent: null, 
    status: 1}] 

[{ _id: 5889a06f274afdfd6f2bf249, 
    cat_id: 1, 
    title: 'Child Category', 
    description: '', 
    parent: 1, 
    status: 1}] 

出力jsonは、mongoDBのdb.find()メソッドを使用してクエリを実行するときにノードを使用する必要があります。

{ 
    obj: [ 
    { 
    _id: "5889a06f274afdfd6f2bf249", 
    cat_id: 1, 
    title: "Parent Category", 
    description: "", 
    parent: null, 
    status: 1, 
    subcategories: [ 
     { 
     _id: "5889a06f274afdfd6f2bf249", 
     cat_id: 1, 
     title: "Child Category", 
     description: "", 
     parent: 1, 
     status: 1 

     } 
    ] 

    } 
]} 
+0

[** '$ graphLookup' **]( https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/#pipe._S_graphLookup)を参照してください。私は、メソッドを呼び出すためのノードで作成したモジュールおよび使用のREST APIを有する – chridam

+0

'//取得カテゴリ module.exports.getCategories =関数(コールバック、限界){ Categories.find(関数(ERR、データ){ } ).limit(制限); } ' とAPI JSから ' app.get( '/ API /カテゴリ'、関数(REQ、RES){ Categories.getCategories(関数(ERR、カテゴリ){ IF(ERR)がこれを呼び出します{ throw err; } res.json(カテゴリ); ) }); –

+0

コードは準備ができていて、結果は間違っていますが、データは正しくありません。 正確に間違いが何であるか理解できません。 'Categories.aggregate([{ $ graphLookup:{ から "カテゴリ"、 startWith: "$親"、 connectFromField: "CAT_ID"、 connectToField: "親"、 として: "サブカテゴリ" } } ]コールバック) ' 親がnullであるカテゴリのリストが存在する必要があります。カテゴリは親カテゴリのcat_idと一致する子としてカテゴリを保持します。 –

答えて

0

以下のように試すことができます。

$startWith各入力文書の表現値はconnectToFieldと一致します。

一致するドキュメントごとに、connectFromFieldの値は、コレクションのconnectToField値と再帰的に一致します。

あなたが使用することができるはずであるのMongoDBのバージョンに応じコレクション

{ "_id" : 1, "cat_id" : 1, "title" : "Parent Category", "parent" : null } 
{ "_id" : 2, "cat_id" : 2, "title" : "Child Category", "parent" : 1 } 
{ "_id" : 3, "cat_id" : 3, "title" : "Sub Child Category", "parent" : 2 } 

クエリ

Categories.aggregate([{ 
    $graphLookup: { 
     from: "categories", 
     startWith: "$cat_id", 
     connectFromField: "cat_id", 
     connectToField: "parent", 
     as: "subCategory" 
    } 
}], callback) 

出力

{ 
    "_id": 1, 
    "cat_id": 1, 
    "title": "Parent Category", 
    "parent": null, 
    "subCategory": [{ 
     "_id": 3, 
     "cat_id": 3, 
     "title": "Sub Child Category", 
     "parent": 2 
    }, { 
     "_id": 2, 
     "cat_id": 2, 
     "title": "Child Category", 
     "parent": 1 
    }] 
} { 
    "_id": 2, 
    "cat_id": 2, 
    "title": "Child Category", 
    "parent": 1, 
    "subCategory": [{ 
     "_id": 3, 
     "cat_id": 3, 
     "title": "Sub Child Category", 
     "parent": 2 
    }] 
} { 
    "_id": 3, 
    "cat_id": 3, 
    "title": "Sub Child Category", 
    "parent": 2, 
    "subCategory": [] 
} 
+0

親のヌルを持つすべてのカテゴリが最初に来て、各ヌルの親のカテゴリに親のIDがそこにcat_idに一致するサブカテゴリがある異なる出力を探しています。以下の出力を参照してください –

関連する問題