I have a CouchDB that syncs to PouchDB in my app. The docs I receive have some set values, but a lot of values may have been added by other parts of the code, and I can not be sure not know which. e.g.
{
"_id": "document-1",
"_rev": "1-967a00dff5e02add41819138abb3284d"
"myData": "AB",
"SomeStuffIdidnotKnow": "1234"
}
So at one point I have to alter a specific value and I thought the easiest way would be doing it like this:
myDB.get("document-1").then(function (doc) {
doc.myData = "ABC";
return CongressData.db.put({
doc
}).then(function (response) {
console.log(response);
}).catch(function (err) {
console.log(err);
});
});
But this always throws an error 412 "missing_id". Of course I know that
return CongressData.db.put({
_id: doc.id,
_rev: doc._rev,
myData: "ABC"
});
would work. But as I cannot say what the other elements are, it would be quite tedious to find out.
Isn't it somehow possible to pass a variable that hold _id an_rev directly to put
?
If I understand correctly, your problem is that there in an inconsistency in the property names.
You can simply loop through the object and convert the keys which need converting. You will probably need to do the reverse operations so recommend a parameterized function:
const couchify = convertKeys(key => to[key] || key);
const to = { id: '_id', revision: '_rev' };
const convertKeys = f => doc => Object.fromEntries(
Object.entries(doc).map(([key, value]) =>
[ f(key), value ]));
You could have a module that contains fixes for this kind of problems which exports a put
function, along other operations which need converting:
export const put = (db, doc) => db.put(couchify(doc))
and use it in place of the stock put
method:
import { put } from 'couchDBAdapter.js';
myDB.get("document-1")
.then(doc => put(CongressData, {...doc, myData: "ABC"}))
.then(console.log, console.error);
You could also wrap your db in a class if that's more your style, but I don't recommend letting this kind of stuff creep up everywhere in your code, for you may want to swap CouchDB for something else at some point.
I didn't test this code.