0

As I am new to CouchDB, I wanted to create the view using a node-couchdb module?

I am able to create a view using UI(Futon), but I want to create a view using node code using a node-couchdb module. Also, how can I add a design document? Is adding document and design document same?

Can anybody please help?

2 Answers2

0

A CouchDB Design Document is just another document except its _id field starts with_design`.

You can create a Design Document by simply inserting it as any other document using the official Apache CouchDB Nano library:

const Nano = require('nano')
const nano = Nano('http://localhost:5984')
const db = nano.db.use('mydb')

const ddoc = {
  "_id": "_design/report",
  "views": {
    "bydate": {
      "reduce": "_count",
      "map": "function(doc) {\n  if (doc.type === 'click') {\n emit(doc.x, doc.y);\n  }\n}"
    }
  },
  "language": "javascript"
}

db.insert(ddoc, function(err, data) {

});
Glynn Bird
  • 5,507
  • 2
  • 12
  • 21
0

We can create views or design document using node-couchdb module as:

couch.insert(_dbname, {
    "_id": "_design/query-demo",
    "views": {
        "full-name": {
            "map": "function (doc) {  emit(doc._id, doc);}"
        }
    },
    "language": "javascript"
});

Here in this example, full-name will be the view name and query-demo will be the design doc name

And we can get the data from that view as:

couch.get(_dbname, '_design/query-demo/_views/full_name', {}).then(({ data, headers, status }) => {
    console.log(data);
    // data is json response
    // headers is an object with all response headers
    // status is statusCode number
}, err => {
    console.log(err);
    // either request error occured
    // ...or err.code=EDOCMISSING if document is missing
    // ...or err.code=EUNKNOWN if statusCode is unexpected
});