0

couchdbを初めて使用する場合、並べ替えと1対多の関係を作成したい

カテゴリ->ドキュメント

カテゴリを並べ替え、各カテゴリ内のドキュメントを並べ替えて、結果を配列として取得したいと考えています。

カテゴリまたはドキュメントのいずれかで並べ替えることができますが、両方で並べ替えることはできません。

クエリ結果として次のようなものを取得したいと思います。

[{  name: 'category1',
    position: 1,
    type: 'category',
    documents: [{ name: ..., type: ..., position: 1 },
                { name: ..., type: ..., position: 2 },
                { name: ..., type: ..., position: 3 }
 }
 {  name: 'category2',
    position: 2,
    type: 'category',
    documents: [{ name: ..., type ..position: 1 },
            { name: ..., position: 2 },
            { name: ..., position: 3 }]
 }]

私はそのようにビューデザインとマップ機能を設定します(これは正しいアプローチですか?):

function(category) { 
  if (type == 'category') {
      for (var d in category.documents) {
          emit([category.position, category.documents[d].position??? ], {_id: category.documents[d], category: category })
      }
  }

問題は...

1- category.documents [d] .positionはまだ「存在しない」ので、単純にそれを行うことはできません。

2-クエリ結果が希望どおりにフォーマットされていません。これは、ドキュメントオブジェクトの配列を持つカテゴリの行ではなく、ドキュメントの行になります。

4

2 に答える 2

1

@OctavianDamiean が指摘したように、ドキュメントにカテゴリ フィールドを追加する必要があります。次に、マップ関数は次のようになります。

function(doc) {
  if (doc.type === 'Document') {
    emit([doc.category, doc.position], 1);
  }
}

でクエリするとinclude_docs=true、次のようになります。

[ { "key": ["category1", 1], "doc": { "name": "doc1.1", "type": "Document", "position": 1 } },
  { "key": ["category1", 2], "doc": { "name": "doc1.2", "type": "Document", "position": 2 } },
  { "key": ["category2", 1], "doc": { "name": "doc2.1", "type": "Document", "position": 1 } },
  { "key": ["category2", 2], "doc": { "name": "doc2.2", "type": "Document", "position": 2 } },
  ...
]
于 2012-08-22T07:46:05.340 に答える
1

CouchDB にはリレーションシップはありません。正しい方法は、ドキュメントが属するカテゴリをドキュメントに直接設定することです。

{
    _id: ...,
    name: ...,
    type: ...,
    category: 1,
    position: 1
}
于 2012-08-21T16:20:52.290 に答える