在一个事务中将多个附件放在PouchDB文档上

时间:2015-01-30 08:34:47

标签: pouchdb

我有一个看起来像这样的功能

var Db = new PouchDB('mydb');

function attach(doc, pictures) {
  // expecting file URI
  var blobPromises = pictures.map(function(imgUri) {
    // https://github.com/nolanlawson/blob-util
    return blobUtil.imgSrcToBlob(imgUri);
  });

  // angular's $q
  return $q.all(blobPromises).then(
    function gotBlobs(blobs) {
      var batchId = (new Date()).getTime();

      var attachPromises = blobs.map(function(blob, i) {
        var attachmentId = 'picture/' + batchId + '/' + i;

        // NOTE: this is throwing error 409
        return Db.putAttachment(doc._id, attachmentId, doc._rev, blob, blob.type);
      });

      return $q.all(attachPromises);
    }
  )
}

现在我知道出了什么问题 - 同样的doc._rev被重复用于所有附件插入。如果我改变我的代码以便一个接一个地执行Db.putAttachment() 并且每次都查询新的doc._rev,它应该会有用。

但是:

  1. PouchDB是否像CouchDB has一样提供putAttachments()之类的API?
  2. 是否可以在通过put()创建文档时放置附件?

1 个答案:

答案 0 :(得分:3)

是的,您可以put()在文档中附加任意数量的附件。

检查第一个示例from the guide。你可以这样做:

db.put({
  _id: 'mydoc',
  _attachments: {
    'myattachment1.txt': {
      content_type: 'text/plain',
      data: blob1
    },
    'myattachment2.txt': {
      content_type: 'text/plain',
      data: blob2
    },
    'myattachment3.txt': {
      content_type: 'text/plain',
      data: blob3
    },
    // etc.
  }
});
相关问题