Search code examples
node.jsexpresscouchdbcloudantcouchdb-nano

Is it possible to dynamically add views in cloudant (couchdb) through node.js using nano


I am using cloudant-couchdb for the first time and I just got stuck with this problem. I am trying to insert a view into my database dynamically through my node.js server.

Here is my code.

app.post("/listSections", function(req, res) {      
  var moduleID = req.body.name;                             
  console.log(moduleID);        
  db.insert(
        { "views":
            { moduleID:     //create view with name = moduleID
                { 
                    "map": function (doc) {
                       //some function
                }
            }
        }, 
        '_design/section', function (error, response) {
                console.log("Success!");        
   });          
});

I want to create a view dynamically with the view name being the value of the variable moduleID. How can I pass that variable in the insert function?


Solution

  • Variable names cannot be interpolated in object literal definitions. Create the object beforehand.

    var obj = {};
    obj[moduleID] = {map: function () {}};
    
    db.insert({views: obj},
    

    If you are using ES6 and computed property names are available, you can do this instead:

    db.insert({views: {[moduleID]: {
    

    See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer