Search code examples
javascriptviewcouchdbrequire

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


Looking at the docs for CouchDB 1.6.1 here, there is mention that you can use the JS require(path) function. How do you do this? The documentation says path is "A CommonJS module path started from design document root".

My design doc is called _design/data. I have uploaded an attachment to this design doc called test.js, which can be accessed at /_design/data/test.js, and contains the following code:

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

But the following code in my map function:

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

results in this error:

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

It looks like require is looking for the path as an object in the docparam... but I don't understand why if it is.

Looking at this link, describing this feature in an older version of CouchDB, it says you can:

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

And gives the following code example:

{
    "_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);
            }
        }
    }
}

But this did not work for me on CouchDB 1.6.1. I get the error:

{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"

Solution

  • In your question you didn't provide the function as a string. It's not too easy to spot, but you must stringify functions before storing them in CouchDB (manually or by using .toString()). Caolan has that error in the post that you linked.