user401377
user401377

Reputation: 53

show all 1M with sorting twice in couchdb?

New to couchdb, I want to do a 1 to Many relationship with sorting

Category -> Documents

Would like to sort Category and sort Documents within each Category and hopefully get the result as an array.

I can sort either by Category or by Documents, but not both.

I would like to get something like this as the query result:

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

I setup a view design and a map function like so (is this the correct approach?):

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

Problems are...

1- category.documents[d].position wouldn't 'exist' yet so I can't simply do that.

2- the query results isn't formatted the way I would want. It would be rows of documents instead of rows of category with a array of document objects.

Upvotes: 0

Views: 61

Answers (2)

Marcello Nuccio
Marcello Nuccio

Reputation: 3901

As pointed out by @OctavianDamiean, you should add a category field in the document. Then the map function becomes something like:

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

Querying with include_docs=true, you'll get:

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

Upvotes: 1

Octavian Helm
Octavian Helm

Reputation: 39604

There are no relationships in CouchDB. The correct way would be to set the category a document belongs to directly on the document.

{
    _id: ...,
    name: ...,
    type: ...,
    category: 1,
    position: 1
}

Upvotes: 1

Related Questions