1

我想更新 couchdb 中的现有文档。我有一张图片,我想将它添加到数据库中的现有文档中,而不会丢失以前的字段。

我正在使用带有 nano 的 nodejs。

坦克,这使我处于正确的方向。最后我这样做:

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);
        });
     }
 });
 });
4

1 回答 1

2

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
    
于 2014-04-26T16:05:51.927 回答