问题
I would like to search trough an array of objects (that are encapsulated in one big object), and emit only the one of the internal objects. So let's suppose I have a JSON inserted into PouchDB that is looks like this:
{
"_id": "5eaa6d20-2019-44e9-8aba-88cfaf8e02542",
"data": [
{
"id": 1452,
"language": "java"
},
{
"id": 18787453,
"language": "javascript"
},
{
"id": 145389721,
"language": "perl"
}
]
}
How to get PouchDB to return the following result when searching for a language with an id = 145389721:
{
"id": 145389721,
"language": "perl"
}
Thanks!
回答1:
In the scenario above the easiest way, using typescript, is to write a temp query:
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);
}
})
Using permanent queries it would have looked like this:
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);
});
来源:https://stackoverflow.com/questions/42636085/pouchdb-emit-object-from-an-array-of-objects