如何干掉CouchDB视图? [英] How do I DRY up my CouchDB views?

查看:126
本文介绍了如何干掉CouchDB视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在CouchDB中的视图之间共享代码?

What can I do to share code among views in CouchDB?

Jesse Hallett 有一些很好的实用方法,包括

Jesse Hallett has some good utility methods, including

function dot(attr) {
  return function(obj) {
      return obj[attr];
  }
}

Array.prototype.map = function(func) {
  var i, r = [],
  for (i = 0; i < this.length; i += 1) {
    r[i] = func(this[i]);
  }
  return r;
};

...

我在哪里可以放置此代码以便每个视图都可以访问它?

Where can I put this code so every view can access it?

类似于我在我的应用程序中使用的常量。我在哪里

Similarly for constants I use in my application. Where do I put

MyApp = {
  A_CONSTANT = "...";
  ANOTHER_CONSTANT = "...";
};



示例3 - 过滤器的过滤器:



如果我想要一个过滤这是一个富人?的视图怎么办?

Example 3 -- filter of a filter:

What if I want a one view that filters by "is this a rich person?":

function(doc) {
  if (doc.type == 'person' && doc.net_worth > 1000000) {
    emit(doc.id, doc);
  }
}

和另一个按姓氏索引:

function(doc) {
  if (doc.last_name) {
    emit(doc.last_name, doc);
  }
}

如何将它们组合成富人姓氏查看?

How can I combine them into a "rich people by last name" view?

我想要相当于Ruby

I sort of want the equivalent of the Ruby

my_array.select { |x| x.person? }.select { |x| x.net_worth > 1,000,000 }.map { |x| [x.last_name, x] }

我怎样才能成为DRYer?

How can I be DRYer?

推荐答案

答案在于 couchapp 。使用couchapp,您可以将包含公共库代码的宏嵌入到任何设计文档部分中。它是在将设计文档提交给服务器之前完成的。你要求做的查询需要做的是反转发出的密钥,这样你就可以在网络上进行范围查询

The answer lies in couchapp. With couchapp you can embed macros that include common library code into any of the design document sections. It is done before the design document is submitted to the server. What you need to do to do the query you ask about is reverse the keys that are emitted so you can do a range query on the "network"

function(doc) 
{
  if (doc.type == 'person') 
  {
    emit([doc.net_worth, doc.lastname], null);
  }
}

您不希望包含您可以使用的文档在查询参数上使用 include_docs = true 执行此操作。并且您可以免费获得doc.id作为密钥的一部分。现在你可以在networth上进行范围查询,看起来像这样。

You don't want to include the doc you can do that with include_docs=true on the query parameters. And you get the doc.id for free as part of the key. Now you can do a range query on networth which would look something like this.

http://localhost:5984/database/_design/people/_view/by_net_worth?startkey=[1000000]&endkey=[{},{}]&include_docs=true

这篇关于如何干掉CouchDB视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆