我想搜索一个对象数组(封装在一个大对象中),并只发出一个内部对象。因此,假设我在PouchDB中插入了一个JSON,如下所示:
{
"_id": "5eaa6d20-2019-44e9-8aba-88cfaf8e02542",
"data" = [
{
"id": 1452,
"language": "java"
},
{
"id": 18787453,
"language": "javascript"
},
{
"id": 145389721,
"language": "perl"
}]
}
如何在搜索id = 145389721的语言时让PouchDB返回以下结果:
{
"id": 145389721,
"language": "perl"
}
谢谢!
答案 0 :(得分:2)
在上面的场景中,使用typescript的最简单方法是编写临时查询:
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 querying the database with an index', error);
});