Tuesday, October 9, 2018

How to get specific data (from an Array) using PouchDB-Find

Leave a Comment

CouchDB document:

  "members": [     {       "name": "Mark",       "age": 35,     },     {       "name": "Bill",       "age": 32,     }   ] 

DB Query from PouchDB using PouchDB-Find:

  db.createIndex({     index: {fields: [       '_id',       'members.[].name'     ]}   }).then(() => {     db.find({       'selector': {         '_id': { '$gt': null },         'members': {           '$elemMatch': {             'name': {'$eq': 'Bill'}           }         }       },       'fields': [         'members'       ]     }).then((result) => {       console.log(result)     }).catch((err) => {       console.log(err)     })   }) 

The result I get from the above query is the Members array as the whole. But I need to get only the below when I request "name" as "Bill" not the complete array.

{   "name": "Bill",   "age": 32, } 

I did try the fields section in the query but I am unable to find what should be mentioned to get what I want.

1 Answers

Answers 1

It is only possible to specify a set of index independent (static) fields in the doc for find to pick once your selector has chosen a given doc.

Mango queries are a simplified syntax to do common cases and when the structure of your indexes and queries is not typical, you need to use map/reduce directly as indicated in the docs:

The map/reduce API is designed for cases that are too complex for Mango queries

So your changes to the first map/reduce example would look something like:

function mapFun(doc) {     if (doc.members)       doc.members.forEach( function(m) {         emit(m.name, m);  // key is name, value is the individual member Object       });   }.toString()   ...   return db.query('index', {     key: 'Bill',     include_docs: false   }); 

To get output like:

 {   "offset" : 0,   "rows": [{     "id": "somedoc",     "key": "Bill",     "value": {name:'Bill', age:32}   }],   "total_rows" : 1 } 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment