Pouchdb 设计视图未正确评估

Pouchdb design view not properly evaluated

我正在使用 pouchdb 作为库为 tiddlywiki 编写一个小型同步适配器。我已经成功地用 couchdb 试验了相同的想法,我认为 pouchdb 应该非常相似,但更好。

除主设计文档的一个特定视图外,一切正常。我刚刚复制了我在 couchdb 上使用的视图,它运行良好,但我遇到了一个愚蠢的错误:未定义字段。这显然是定义的!这是我的查看代码:

function (doc) {
        fields = {};
        for(var field in doc.fields ){
            //text should not be included, neither title. We also avoid to send too long fields
         if( ['text','title'].indexOf(field) === -1 && doc.fields[field].length < 1024){
            fields[field] = doc.fields[field];
         }
        }
        fields.revision = doc._rev; //required for proper sync 
    emit(doc._id,fields);
}

如您所见,我要做的第一件事是定义字段。我尝试添加 var fields 结果是一样的。这真让我抓狂。如果我想让它起作用,我必须将所有内容都加入同一行。我的目标是将这个函数外部化到一个文本文档中,以便能够轻松地编辑它,所以我可以这样做:

var My_view=DoWatheverToGetTheText();
var design_document = {
  '_id': '_design/tw',
  'views': {
    'skinny-tiddlers': {
      'map': My_view
    }}
  };

我试过了,但我得到了完全相同的错误。我不希望将其硬编码到我的应用程序中,我希望它是模块化的。我做错了什么?

最后我自己找到了解决方案。

我的做法是,首先,将设计文档分成两个文件。一个只有设计文档定义,没有地图功能,但在其位置上有一个空的 属性。确保此文档有效非常重要 JSON,这是我的问题之一。

{"_id": "_design/TiddlyPouch",
  "views": {
    "someView": {
      "map": ""
    }},
    "filters": {
      "tiddlers" : ""
}
  }

然后我将地图函数(只是没有名字的函数)写到另一个文件中。它看起来像这样:

function(doc){
var fields = {};  
for(var field in doc.fields ){ 
    if( ['text','title'].indexOf(field) === -1){
        fields[field] = doc.fields[field];
    }
}
fields.revision = doc._rev;
emit(doc._id,fields);
 }

为了让它们都合适,我先评估了设计文档,得到了一个设计对象。然后,我以纯文本形式获取函数并加入它,没有任何回车 return。基本上我把它写成一行。然后你所要做的就是把那个纯文本的函数作为地图的值 属性:

stringContainingFunction = functiontext.replace(/\r?\n/,' ');
designDocument.views.someView.map = stringContainingFunction;

之后直接push对象到pouchdb,效果不错

As you can see, the first thing that I'm doing is to define the fields.

猜测:您缺少 fields = {}; 的 var 关键字。当运行 javascript in strict mode时,这将导致引用错误。