Document update error while inserting views dynamically in cloudant couchdb

315 Views Asked by At

I am using a nosql database(cloudant-couchdb) for the first time and it has been going good so far. But I am stuck with these two problems:

  1. I am trying to add views dynamically. I am able to add the first view, but I get errors while trying to insert more views stating Document update conflict. How would it be an 'update' since I am inserting a new view everytime and not updating it?

  2. Is it possible to pass a parameter in a map function? Something like - if(doc.name == someVariable)?

Here is my code below:

app.put("/listSections", function(req, res) {
    var module = req.body.name;
    var obj = {};
    obj[module] = { "map": function (doc) {
        if (doc.name == "Developer") {
            //emit something
        }
    }
});
db.insert({views: obj}, 
    '_design/section', function (error, response) {
        if (error) {
            console.log("error: " + error);
        }
        console.log("module: " + module );
    }
);
1

There are 1 best solutions below

0
On BEST ANSWER

My approach was wrong. I just found creating multiple views is a bad practice. So I created one (general) view, and passed queries as parameters that answer my second question (how to pass dynamic parameters). Here is what I did:

app.get("/listSections", function(req, res) {
    var moduleId = req.query.id;
    db.view('section','getSections', { key: moduleId }, function(err, body)
   {
       //store values
   }
}

Here I pass the moduleId dynamically to my map function that sets the key as moduleId. Also, I found this link to be pretty useful for couchdb queries - http://sitr.us/2009/06/30/database-queries-the-couchdb-way.html