2017-03-06 45 views
1

我想搜索槽對象數組(封裝在一個大對象中),並只發出一個內部對象。因此,讓我們假設我有插入PouchDB這是一個JSON看起來是這樣的:PouchDB從對象數組中發射對象

{ 
"_id": "5eaa6d20-2019-44e9-8aba-88cfaf8e02542", 
"data" = [ 
    { 
    "id": 1452, 
    "language": "java" 
    }, 
    { 
    "id": 18787453, 
    "language": "javascript" 
    }, 
    { 
    "id": 145389721, 
    "language": "perl" 
    }] 
} 

如何獲得PouchDB爲一個id = 145389721語言搜索時返回以下結果:

{ 
    "id": 145389721, 
    "language": "perl" 
    } 

謝謝!

回答

2

在最簡單的方法上面的場景中,使用打字稿,是寫一個臨時查詢:

 db.query((doc, emit) => { 
      for (let element of doc.data) { 
      if (element.id === 145389721) { 
       emit(element); 
      } 
      } 
     }).then((result) => { 
      for (let row of result.rows) { 
      console.log(row.key); 
      } 
     }) 

使用永久查詢,它會是這個樣子的:

let index = { 
    _id: '_design/my_index', 
    views: { 
    "by_id": { 
     "map": "function(doc) {for (let element of doc.data) {emit(element.id, element); }}" 
    } 
    } 
}; 

// save it 
this.db.put(index).catch(error => { 
    console.log('Error while inserting index', error); 
}); 

//query it 
this.db.query('my_index/by_id', { startkey: 145389721, endkey: 145389721}).then(result => { 
    for (let row of result.rows) { 
    console.log(row.value); 
    } 
}).catch(error => { 
    console.log('Error while quering the database with an index', error); 
});