PouchDB使用参数进行查询

7

假设我们在PouchDB中存储汽车(大约40MB),表示为JSON对象,并且我们想要基于马力属性进行搜索。例如在sql中:select * from cars where HP > 100。

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

据我所知,map函数可以实现此功能,

function(doc) {
  if(doc.value) {
    emit(doc.value, null);
  }
}

无法访问函数外部作用域中的任何变量。

var horsePower = $scope.horsePowerInputField

function(doc) {
  if(doc.hp > horsePower) {
    emit(doc.value, null);
  }
}

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

4个回答

9
截至PouchDB 2.0.0,map/reduce查询中支持闭包。详情请见
然而,如果可以的话,您应该避免使用它们,因为:
  1. 仅PouchDB支持,CouchDB不支持
  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);
  }
}

3

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

在PouchDB中,视图不是持久的,因此您的查询始终查看数据库中的每个文档,并且您必须在map函数之后进行过滤。类似这样的:

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)
}

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


2

最好不要使用闭包。改用以下方法:

var horsePower = $scope.horsePowerInputField;
db.query(function(doc) {emit(doc.hp)}, {startkey: horsePower, include_docs: true});

0

你可以使用全局变量的技巧

var getTimesheetId = '';  //global Variable
var getOfflineTimesheet= function(documentId){
getTimesheetId = documentId;   // assigning the value of the parameter to the global variable


var map= function(doc){
        if(doc.timesheet){
            console.log(getTimesheetId);   // here the map function is able to get the value of the global variable, which is essentially the parameter.
            if (doc._id == getTimesheetId){ 
                emit(doc._id, doc.timesheet);
            }
        }
    };

db.query({map: map}, function(err, res){
        if(!err){
            var out= "";
            res.rows.forEach(function(element){
                console.log(element.value);
            });

        }
    })
  };

你将调用它的方式是

getOfflineTimesheet('timesheet1DocId'); getOfflineTimesheet('timesheet2DocId'); getOfflineTimesheet('timesheet3DocId');


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