Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PouchDB: update document with modified object

I use Pouchdb to create a database from user data and I would like to update a document with a modified object. For example, I have this initial object:

var doc = {
    "_id": "test",
    "trial": 0,
    "results": [11, 22, 33]
};

Then I modify it:

doc.results[doc.results.length] = 44;

I would like to replace the old doc with the new. I tried these steps:

1/ Initialize PouchDB and the document

var db = new PouchDB('test');
var doc = {
    "_id": "test",
    "trial": 0,
    "results": [11, 22, 33]
};

2/ Put the initial document in the database

db.put(doc);

3/ Modify the document

doc.results[doc.results.length] = 44;

4/ Try to update the database with the new doc

db.get('test').then(function(doc) {
      return db.put(doc);
    }).then(function () {
      return db.get('test');
    }).then(function (doc) {
      console.log(doc);
    });

But the document in the database is not modified.

How can I update the doc with the modified object?

UPDATE:

I can't make the update work even with the _rev. As suggested by mauritslamers, I tried to include the _rev in the doc:

var db = new PouchDB('test');
var doc = {
    "_id": "test",
    "_rev": 0,
    "trial": 0,
    "results": [11, 22, 33]
};

And in the put statement with the following:

db.get('test').then(function(doc) {
      return db.put(doc, doc._rev);
    }).then(function () {
      return db.get('test');
    }).then(function (doc) {
      console.log(doc);
    });

But it doesn't work.

like image 754
hhh Avatar asked Oct 14 '25 04:10

hhh


1 Answers

Your code should be:

db.get('test').then(function(doc) {
      return db.put(doc); // <-- no need to include rev as the second argument
    }).then(function () {
      return db.get('test');
    }).then(function (doc) {
      console.log(doc);
    });
like image 103
nlawson Avatar answered Oct 16 '25 17:10

nlawson