Question

I want to update an existing document in couchdb. I have an image and i want to add it to an existing document in the db without lose the previus fields.

I'm using nodejs with nano.

tanks, this put me in the right orientation. At the end i do it in this way:

db.get(id,{ revs_info: true }, function (error, objeto) {
    if(error)
       console.log('wrong id');
fs.readFile('image.jpg', function(err, data) 
    {
     if (!err) 
     {
        db.attachment.insert(id, 'imagen.jpg', data, 'image/jpg',{ rev: objeto._rev}, function(err, body) { 
             if (!err)
                console.log(body);
        });
     }
 });
 });
Was it helpful?

Solution

Your question is not really clear about the specific problem. So here just some general guidance on updating documents.

  • When designing the database make sure you set the ID rather than allowing couchdb to edit it. This way you can access the document directly when updating it.
  • When updating, you are required to prove that you are updating the most recent version of the document. I usually retrieve the document first and make sure you have the most recent '_rev' in the document you'll insert.
  • finally the update may fail if a different process has edited the document in the time between retrieving and updating it. So you should capture a failure in the insert and repeat the process until you succeed.

That being said, there are two ways you can store an image:

  1. As an attachment: I believe nano support the attachment.insert() and attachment.get() functions to do so.
  2. As a reference: I would usually rather store the images elsewhere and just store the url or filepath to access them. I've not used nano much but believe you can do this by doing the below.

    doc = db.get(docname); // get the document with all existing elements 
    doc['mynewimage'] = myimageurl; // update the document with the new image
                                    // this assumes it's a dictionary
    db.insert(doc); // inserts the document with the correct _id (= docname)
                    // and _rev
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top