Question

Say that there is a couchdb session opened through nano on node.js

var dbserv = require('nano')('http://localhost:5984');

At the couchdb server dbserv can access, there is a database users with users that have a field groups that is an array.

If I wanted to update groups on a user jim in users, how would I do so without replacing the entire document?

Was it helpful?

Solution

CouchDB

To create an update handler, write a design document:

{
  "_id": "_design/yourapp",
  "updates": {
    "foo": "function(doc, req) {
      doc.groups.push(req.query.bar); // or do whatever you like with it
      return [doc, 'done'];
    }"
  }
}

and PUT it in your db with the id _design/yourapp, then GET it like this:

http://localhost:5984/users/_design/yourapp/_update/foo/jim?bar=baz

nanocouch

var dbserv = require('nano')('http://localhost:5984');
var db = dbserv.use('users');

var designdoc = {/* The above design document */};

db.insert(designdoc);

db.get('_design/yourapp/_update/foo/jim', {bar: 'baz'});

Note that you need to insert the design document only once, you can even do it manually using curl, then to update your docs just make a GET request as explained above.

Disclaimer: untested and I never used nano before, but it should be on the lines of what you have to do.

OTHER TIPS

Found a way to make updates, without all _design needs and such. The issue with Nano CouchDB is that the insert doesn't really provide a place to send the correct _rev that is needed for an update. Anyhow, there is a work around. What one needs to do, is to get the _rev value from the _id you want to update. So you use Nano db.get as the big function, get the _rev value and update your document. Here is a code sample:

 users.get('document_name', function(err, doc) {
        updaterev = doc._rev;
        users.insert({title:'here_ya_go',_rev:updaterev},'document_name', function(err, body , header) {
            if (!err)
            {
                console.log(body);
                res.send('update website succeed');
            }
            else
            {
                console.log(err.error);
            }
        });
  });

When the db.insert functions are inside db.get function, it gives us a chance to grab hold of the _rev and update out document.

I know, I probably didn't invent this, but it's important to have this piece of code to grab and go. Good luck.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top