1

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Kashif Kai
  • 33
  • 5

1 Answers1

1

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

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • You are absolutely right. Thank you so much. However, I am only able to add a single view with it. It won't add new views (with different moduleID's) on multiple post requests. – Kashif Kai Jun 24 '15 at 20:19
  • This code works, but only for the first view. It wont add views after the first name - "Error: Document update conflict". – Kashif Kai Jun 25 '15 at 14:04
  • @KashifKai views must have unique names. If you want to create another view, it needs a different name (or you must delete the original view) – Explosion Pills Jun 25 '15 at 14:33