Creating view in Cloudant (CouchDB) based on an object property value

后端 未结 3 1373
心在旅途
心在旅途 2021-01-06 04:21

I\'ve been trying to find a solution for this requirement but I\'ve hit many dead ends.

I\'m using Cloudant as my data store of user documents. Each

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-06 05:11

    In CouchDB you can't pass in a dynamic value for a query parameter to a view (in your case cat=determination). The approach in CouchDB is to create a more general view, and then adjust how the result is sorted when you call the view to get at the data you need.

    You'll need to create custom view in your db's design document to achieve this:

    byUserItemCat: {
        map: function (doc) {
            if ( !doc.items || doc.items.length === 0 ) return;
            for ( var i=0; i

    So the above view takes each doc in the db, checks it has an items array with contents, and then loops over all the doc's items. For each item element it finds it emits cat into the result set as the index, this is important since we can then sort against against this index. We're free to build the result object in anyway we like (second argument to emit), and in the above case I'm building an object with the user id, and the item's date and text.

    You'd call the view something like this, to get all the results:

    curl -X GET http://127.0.0.1:5984//_design//_view/byUserItemCat
    

    And if you were just interested in the results where the index key (i.e. cat) was "determination" you'd do:

    curl -X GET http://127.0.0.1:5984//_design//_view/byUserItemCat?key="determination"
    

提交回复
热议问题