Reputation: 2003
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.
Upvotes: 4
Views: 4984
Reputation: 8962
It looks like a scope issue.
You've used the same object name 'doc' for your modified document (in the outer/global scope) and modified it outside your get/put promise block (which also had a local scope 'doc' object that took precedence over your modified doc object).
i.e. You were GETTING your old document and then PUTTING it straight back...thus it didn't appear to change.
To make it work:
var db = new PouchDB('test');
var doc = {
"_id": "test",
"trial": 0,
"results": [11, 22, 33]
};
db.put(doc); // initial put
db.get('test').then(function(doc) {
doc.results[doc.results.length] = 44; // modify it here instead
return db.put(doc);
}).then(function () {
return db.get('test');
}).then(function (doc) {
console.log(doc);
});
Upvotes: 1
Reputation: 11620
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);
});
Upvotes: 4
Reputation: 527
Just based on your code I would suspect that you didn't include the _rev in the doc, or in the put call. If I remember correctly, PouchDB works like CouchDB and will require a revision number before successfully updating a document.
Upvotes: 1