0

Is it possible to add an attachment to an existing doc? When I use:

db.putAttachment()

I get an conflict error...

Nate
  • 7,606
  • 23
  • 72
  • 124

3 Answers3

1

When you attach an attachment to a document, you still need to pass in the rev of the existing doc, because it's considered a modification to the document.

nlawson
  • 11,510
  • 4
  • 40
  • 50
1

I always found it useful to create an addOrUpdate() type of function to deal with pouch. It basically tries to find an entry with the id you pass, if its not found, it will create, otherwise it will update

function addPouchDoc(documentId, jsonString) {
var pouchDoc = {
    _id: documentId,
    "pouchContent": jsonString,
};

// var test = db.get(documenId, function(err, doc) { });  alert(test);
db.put(pouchDoc, function callback(err, result) {
    if (!err) {
        console.log('Successfully added Entry!');

    } else {
        console.log(err);
    }

});  
}

Here is the function you should always call

function addOrUpdatePouchDoc(documentId, jsonString) {


var pouchDoc = {
    _id: documentId,
    "pouchContent": jsonString
};


db.get(documentId, function(err, resp) {

    console.log(err);
    if (err) {
        if (err.status = '404') {
            // this means document is not found
            addPouchDoc(documentId, jsonString);

        }
    } else {
        // document is found OR no error , find the revision and update it
        //**use db.putAttachment here**

        db.put({
            _id: documentId,
            _rev: resp._rev,
            "pouchContent": jsonString,
        }, function(err, response) {
            if (!err) {
                console.log('Successfully posted a pouch entry!');
            } else {
                console.log(err);
            }

        });


    }



});  
}
0

You need to pass the _id and _rev of the document the attachment will be placed in.

 db.putAttachment(_id.toString(), file_name, _rev.toString(), qFile.data, type )
  .then((result) =>{
      console.log(result)
      }).catch((err) => {
      console.log(err)
  });

Where qFile.data represents the blob, or 64bit data string in this case, and type represents the mimetype such as 'image/png', or 'text/json' etc.

https://pouchdb.com/api.html#save_attachment

and a good, but dated live example here: https://pouchdb.com/guides/attachments.html

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Ned Studt
  • 11
  • 1