Search code examples
javascriptnode.jscouchdbcouchdb-nano

CouchDB Cannot update a Document via nano module


I'm using This Node.js module nano

Why I Can't Update my Document? I will Want to Make crazy: true and then False again.
This is My Code:

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

// clean up the database we created previously
nano.db.destroy('alice', function() {
  // create a new database
  nano.db.create('alice', function() {
    // specify the database we are going to use
    var alice = nano.use('alice');
    // and insert a document in it
    alice.insert({ crazy: true }, 'rabbit', function(err, body, header) {
      if (err) {
        console.log('[alice.insert] ', err.message);
        return;
      }
      console.log('you have inserted the rabbit.')
      console.log(body);
    });
  });
});

Solution

  • Nano doesn’t come with an update method by default. That is why we need to define a custom method that would do it for us. Declare the following near the top of your app.js file, right after your database connection code.

    test_db.update = function(obj, key, callback){
     var db = this;
     db.get(key, function (error, existing){ 
        if(!error) obj._rev = existing._rev;
        db.insert(obj, key, callback);
     });
    }
    

    You can then use the update method in your code:

        // and update a document in it
        alice.update({ crazy: false }, 'rabbit', function(err, body, header) {
          if (err) {
            console.log('[alice.insert] ', err.message);
            return;
          }
          console.log('you have updated the rabbit.')
          console.log(body);
        });
      });
    });