PouchDB从一个对象数组中发出对象。

3

我希望能够搜索一个对象数组(这些数组封装在一个大对象中),并仅发出内部对象之一。假设我有一个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"
}

谢谢!

1个回答

3
在上述情况下,使用 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);
});

如果我使用您的技术而不是使用JS迭代数组,是否会获得一些性能优势?(假设我的集合中只有20-30条记录) - Phantom007

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接