node.jscouchdbcouchdb-futon

Creating Views using node-couchdb module


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?


Solution

  • 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
    });