How do I update a doc in Cloudant using Cloudant Node.js

Creights picture Creights · Jul 10, 2015 · Viewed 7.4k times · Source

So, what I'm doing should be really simple, and maybe it is and I'm just doing something wrong. I want to update an existing document in my database but I'm having some issues, can someone please advise?

Nano's Documentation states the following for insert:

db.insert(doc, [params], [callback])

Therefore, I should surely be able to do the following:

 var user = {
   'firstname' : 'my',
   'secondname' : 'name'
};

db.insert(user, {_rev: '2-cc5825485a9b2f66d79b8a849e162g2f'}, function(err, body) {}); 

However, whenever I try this, it creates an entirely new document. If I do the following then it will indeed update my document, but of course, with nothing in this document other than the _rev:

db.insert({_rev: '2-cc5825485a9b2f66d79b8a849e162g2f'}, function(err, body) {});

So the question is, how do I pass in my object and get it to update, rather than creating a new record?

Answer

Nicholas Tsaoucis picture Nicholas Tsaoucis · Nov 15, 2016
var user = {
   'firstname' : 'my',
   'secondname' : 'name',
   '_id': <id from prev object>,
   '_rev': <rev from prev object>
};

db.insert(user, function(err, body) {}); 

the _id and _rev are both required in order for the update to work. they should be in the object that you are sending also.