【问题标题】:Creating Views using node-couchdb module使用 node-couchdb 模块创建视图
【发布时间】:2018-12-31 17:00:27
【问题描述】:

由于我是 CouchDB 的新手,我想使用 node-couchdb 模块创建视图?

我可以使用 UI(Futon) 创建视图,但我想使用 node-couchdb 模块使用节点代码创建视图。 另外,如何添加设计文档? 添加文档和设计文档是一样的吗?

有人可以帮忙吗?

【问题讨论】:

    标签: node.js couchdb couchdb-futon


    【解决方案1】:

    我们可以使用 node-couchdb 模块创建视图或设计文档:

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

    在此示例中,full-name 将是视图名称,query-demo 将是设计文档名称

    我们可以从该视图中获取数据:

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

    【讨论】:

      【解决方案2】:

      CouchDB 设计文档只是另一个文档,除了它的 _id 字段以 with_design 开头。

      您可以通过使用官方Apache CouchDB Nano 库将其作为任何其他文档简单地插入来创建设计文档:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多