使用参数进行PouchDB查询

Fra*_*ier 6 pouchdb

让我们假设我们在PouchDB中存储表示为JSON对象的汽车(大约40MB),我们希望根据马力属性进行搜索.sql中的示例:select*from HP> 100的汽车.

您可以按键查询pouchDB,但显然HP不是文档的关键.有没有办法可以做到这一点?

据我了解地图功能,

function(doc) {
  if(doc.value) {
    emit(doc.value, null);
  }
}
Run Code Online (Sandbox Code Playgroud)

无法访问函数外部范围内的任何变量.

var horsePower = $scope.horsePowerInputField

function(doc) {
  if(doc.hp > horsePower) {
    emit(doc.value, null);
  }
}
Run Code Online (Sandbox Code Playgroud)

那么有可能查询数据库,基于非关键变量进行参数化吗?

nla*_*son 8

PouchDB 2.0.0开始,支持map/reduce查询中的闭包. 细节在这里.

但是,如果可以,你应该避免使用它们,因为

  1. 它们不受CouchDB支持,只有PouchDB支持
  2. 保存的map/reduce视图更快,可能会在2.1.0中添加,不能支持闭包.

话虽这么说,如果你想使用闭包,你现在可以这样做:

var horsePower = $scope.horsePowerInputField

function(doc, emit) { // extra 'emit' tells PouchDB to allow closures
  if(doc.hp > horsePower) {
    emit(doc.value, null);
  }
}
Run Code Online (Sandbox Code Playgroud)


jch*_*hes 3

你的map函数失去了它的闭包,因为它在 PouchDB 内部被重新评估(这就是它获取函数的方式emit)。这意味着您无法从代码中访问任何变量,但仍然可以查询数据库。

在 PouchDB 中,视图不是持久的,因此您的查询总是查看数据库中的每个文档,并且必须在映射函数之后进行过滤。像这样的东西:

function findCars(horsePower, callback) {
  // emit car documents
  function map(doc) {
    if(doc.type == 'car' && doc.value) {
      emit(doc.value, null);
    }
  }

  // filter results
  function filter(err, response) {
    if (err) return callback(err);

    var matches = [];
    response.rows.forEach(function(car) {
      if (car.hp == horsePower) {
        matches.push(car);
      }
    });
    callback(null, matches);
  }

  // kick off the PouchDB query with the map & filter functions above
  db.query({map: map}, {reduce: false}, filter)
}
Run Code Online (Sandbox Code Playgroud)

是解决这个问题的一种方法。Pouch 将迭代每个文档,将其传递给您的map函数。完成后,filter将使用所有发出的文档的数组进行调用。filter不会丢失其关闭上下文,因此您可以在此处根据马力或任何其他字段过滤结果。