0 votes
in PouchDB by
How to Create/update a batch of documents in PouchDB?

1 Answer

0 votes
by

db.bulkDocs(docs, [options], [callback])

Create, update or delete multiple documents. The docs argument is an array of documents.

If you omit an _id parameter on a given document, the database will create a new document and assign the ID for you. To update a document, you must include both an _id parameter and a _rev parameter, which should match the ID and revision of the document on which to base your updates. Finally, to delete a document, include a _deleted parameter with the value true.

Example Usage:

Put some new docs, providing the _ids:

db.bulkDocs([ {title : 'Lisa Says', _id: 'doc1'}, {title : 'Space Oddity', _id: 'doc2'} ]).then(function (result) { // handle result }).catch(function (err) { console.log(err); });

Post some new docs and auto-generate the _ids:
db.bulkDocs([
  {title : 'Lisa Says'},
  {title : 'Space Oddity'}
]).then(function (result) {
  // handle result
}).catch(function (err) {
  console.log(err);
});Example Response:
    "ok": true,
    "id": "doc1",
    "rev": "1-84abc2a942007bee7cf55007cba56198"
    "ok": true,
    "id": "doc2",
    "rev": "1-7b80fc50b6af7a905f368670429a757e"
  }
]The response contains an array of the familiar ok/rev/id from the put()/post() API. If there are any errors, they will be provided individually like so:
[ { status: 409,
    name: 'conflict',
    message: 'Document update conflict',
    error: true
  }
]The results are returned in the same order as the supplied “docs” array.

Note that bulkDocs() is not transactional, and that you may get back a mixed array of errors/non-errors. In CouchDB/PouchDB, the smallest atomic unit is the document.

Bulk update/delete:

You can also use bulkDocs() to update/delete many documents at once:

db.bulkDocs([ { title : 'Lisa Says', artist : 'Velvet Underground', _id : "doc1", _rev : "1-84abc2a942007bee7cf55007cba56198" }, { title : 'Space Oddity', artist : 'David Bowie', _id : "doc2", _rev : "1-7b80fc50b6af7a905f368670429a757e" } ]).then(function (result) { // handle result }).catch(function (err) { console.log(err); });

Or delete them:

db.bulkDocs([
  {
    title    : 'Lisa Says',
    _deleted : true,
    _id      : "doc1",
    _rev     : "1-84abc2a942007bee7cf55007cba56198"
    title    : 'Space Oddity',
    _deleted : true,
    _id      : "doc2",
    _rev     : "1-7b80fc50b6af7a905f368670429a757e"
  }
]).then(function (result) {
  // handle result
}).catch(function (err) {
  console.log(err);
});
Note: If you set a 

Related questions

0 votes
asked Jun 5, 2020 in PouchDB by AdilsonLima
0 votes
asked Jun 5, 2020 in PouchDB by AdilsonLima
...