如何在 map 函数中使用 require() ?

How do you use require() within a map function?

查看 CouchDB 1.6.1 的文档 here,其中提到您可以使用 JS require(path) 函数。你怎么做到这一点?文档说 path 是 "A CommonJS module path started from design document root".

我的设计文档叫做 _design/data。我已经上传了一个附件到这个名为 test.js 的设计文档,可以在 /_design/data/test.js 访问它,它包含以下代码:

exports.stuff = function() {
    this.getMsg = (function() {
        return 'hi';
    })()
}

但是我的地图函数中的代码如下:

function(doc) {
  try {
    var x = require('test.js');
  } catch (e) {
   emit ('error', e)
  }
}

导致此错误:

["error", "invalid_require_path", "Object has no property \"test.js\". {\"views\":{\"lib\":null},\"_module_cache\":{}}"]

看起来 require 正在 doc 参数中寻找作为对象的路径...但我不明白为什么是这样。

查看 this link,在旧版本的 CouchDB 中描述了此功能,它说您可以:

However, in the upcoming CouchDB 1.1.x views will be able to require modules provided they exist below the 'views' property (eg, 'views/lib/module')

并给出如下代码示例:

{
    "_id": "_design/example",
    "lib": {
        // modules here would not be accessible from view functions
    },
    "views": {
        "lib" {
            // this module is accessible from view functions
            "module": "exports.test = 'asdf';"
        },
        "commonjs": {
            "map": function (doc) {
                var val = require('views/lib/module').test;
                emit(doc._id, val);
            }
        }
    }
}

但这在 CouchDB 1.6.1 上对我不起作用。我收到错误:

{message: "mod.current is null", fileName: "/usr/share/couchdb/server/main.js", lineNumber: 1137, stack: "([object Array],[object Object])@/usr/share/couchdb/server/main.js:1137\n([object Array],[object Object])@/usr/share/couchdb/server/main.js:1143\n([object Array],[object Object],[object Object])@/usr/share/couchdb/server/main.js:1143\n(\"views/lib/module\")@/usr/share/couchdb/server/main.js:1173\n([object Object])@undefined:3\n([object Object])@/usr/share/couchdb/server/main.js:1394\n()@/usr/share/couchdb/server/main.js:1562\n@/usr/share/couchdb/server/main.js:1573\n"

使用这个例子:

  15    views: {
  16      lib: { 
  17        foo: "exports.bar = 42;" 
  18      },
  19      test: { 
  20        map: "function(doc) { emit(doc._id, require('views/lib/foo').bar); }"
  21      }
  22    }

在此处的旧 CouchDB 文档中找到:https://wiki.apache.org/couchdb/CommonJS_Modules

我得到了一个有效的例子。不确定真正的区别是什么...我是 运行 'temp' 视图而不是保存,但我不知道为什么这会影响 require 语句

在您的问题中,您没有将函数作为字符串提供。这不太容易发现,但您必须先将函数字符串化,然后再将它们存储在 CouchDB 中(手动或使用 .toString())。 Caolan 在您链接的 post 中有错误。