0 votes
in PouchDB by

Create/update a document

Using db.put()

db.put(doc, [options], [callback])

Create a new document or update an existing document. If the document already exists, you must specify its revision _rev, otherwise a conflict will occur.

If you want to update an existing document even if there’s conflict, you should specify the base revision _rev and use force=true option, then a new conflict revision will be created.

doc must be a “pure JSON object”, i.e. a collection of name/value pairs. If you try to store non-JSON data (for instance Date objects) you may see inconsistent results.

Example Usage:

Create a new doc with an _id of 'mydoc':

db.put({
  _id: 'mydoc',
  title: 'Heroes'
}).then(function (response) {
  // handle response
}).catch(function (err) {
  console.log(err);
});

You can update an existing doc using _rev:

db.get('mydoc').then(function(doc) {
  return db.put({
    _id: 'mydoc',
    _rev: doc._rev,
    title: "Let's Dance"
  });
}).then(function(response) {
  // handle response
}).catch(function (err) {
  console.log(err);
});

Example Response:

{
  "ok": true,
  "id": "mydoc",
  "rev": "1-A6157A5EA545C99B00FF904EEF05FD9F"
}

The response contains the id of the document, the new rev, and an ok to reassure you that everything is okay.

Using db.post()

db.post(doc, [options], [callback])

Create a new document and let PouchDB auto-generate an _id for it.

Example Usage:

db.post({
  title: 'Ziggy Stardust'
}).then(function (response) {
  // handle response
}).catch(function (err) {
  console.log(err);
});

Example Response:

{
  "ok" : true,
  "id" : "8A2C3761-FFD5-4770-9B8C-38C33CED300A",
  "rev" : "1-d3a8e0e5aa7c8fff0c376dac2d8a4007"
}

Put vs. post: The basic rule of thumb is: put() new documents with an _id, post() new documents without an _id.

You should also prefer put() to post(), because when you post(), you are missing an opportunity to use allDocs() to sort documents by _id (because your _ids are random). 

Related questions

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