Please confirm this is the only way I can update a document in couchDB;
In order to update a document (lets call it fooDoc) I NEED TO pass "_rev". so fisrt I need to fetch that document by following code (foo.get) and then in the callback when I have the "_rev" I can use foo.insert to update that document on the last revision:
var foo = nano.db.use('foo');
foo.get('fooDoc', function (err, body) {
console.log("get:", err, body);
foo.insert({"_id": "fooDoc", "_rev": body['_rev'], "name": "newName", "bar": "baz"}, function (err, body) {
console.log("insert:", err, body);
})
});
UPDATED:
Thanks Nuno for your help: So I was following this documentation; however it seems the json format for update handler is not a valid json, so I updated to the following json:
{
"updates": {
"inplace": "function(doc, req) {var field = req.form.field;var value = req.form.value;var message = 'set '+field+' to '+value;doc[field] = value;return [doc, message];}"
}
}
And now when I run the following code it is not updating and the following is the log:
error: null respose: set undefined to undefined
The code:
foo.atomic("update", "inplace", "bar6",
{crazy: true}, function (error, response) {
console.log("error:", error, "respose:", response)
});
I really appreciate your help in this regard
FINAL UPDATE: Oh I figured out the problem; the update handler from hereenter link description here is not right; the right update handler would be:
{
"inplace": "function (doc, req) {var message;var body=JSON.parse(req.body);for (id in body) {doc[id] =body[id];message += 'set ', id, 'to', body[id];}return[doc,message];}"
}
The only way of updating a document without previous knowledge of the _rev number is through an update function.
In nano, update functions are called with db.atomic
.
But you don't necessarily need to fetch the entire document, just the _rev.
As Mike said, to get the _rev of a single document you can issue a HEAD request. The _rev will be in the ETag header. In nano use db.head
.
You can also fetch the _rev for multiple documents in one go by querying _all_docs. In nano use db.list
.