簡體   English   中英

PouchDB從對象數組中發出對象

[英]PouchDB emit object from an array of objects

我想搜索一個對象數組(封裝在一個大對象中),並只發出一個內部對象。 所以我假設我在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"
}

謝謝!

在上面的場景中,使用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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM