Hello.
I am trying to subtract some values from a collection and upsert the values in a new collection. So far i got a code that is working, but it do give alot of errors, and I guess i have not made a very good solutin. First of all i try to send a field and its value to a new collection, and I need to keep the same meta id.
- If the document is not excisting i want to create it. And insert the field.
- If the document is excisting i want to create the field.
- If the field is excisiting i want to update the value.
The working code i got so far:
function OnUpdate(doc, meta) {
log('Running OnUpdate for doc ID: ' + meta.id);
function get(data) {
let results = [];
Object.keys(data).forEach(key => {
if (data[key] && typeof data[key] === 'object' && data[key].hasOwnProperty('type') && Array.isArray(data[key].value)) {
const values = data[key].value.map(priceObj => parseFloat(priceObj.value));
const highestValue = Math.max(...values);
results.push({ type: data[key].type, value: value});
}
});
return results;
}
const results = valueAndPrice(doc);
const metaObj = { id: meta.id };
const mutateOps = results.map(result => {
log(`Adding operation to upsert ${result.type} with value ${result.value}`);
return couchbase.MutateInSpec.upsert(result.type, result.value);
});
try {
const mutateResult = couchbase.mutateIn(dst_bucket, metaObj, mutateOps);
log('Document updated in a batch: ' + JSON.stringify(mutateResult));
} catch (error) {
log(`Error updating document in a batch. Attempting to create a new document.`);
let newDoc = {};
results.forEach(result => {
newDoc[result.type] = result.value;
});
try {
const insertResult = couchbase.insert(dst_bucket, metaObj, newDoc);
log('New document created: ' + JSON.stringify(insertResult));
} catch (insertError) {
log(`Error creating new document: ${JSON.stringify(insertError)}`);
}
}
}
The errors:
- At the moment i just got to pray the error is caused of missing document, so I feel this is not a good solution.
- The code is working but is producing equal errors and success:
The error i get: “New document created: {"error":{"code":2,"name":"LCB_KEY_EEXISTS","desc":"The document key already exists in the server.","key_already_exists":true},"success":false}”
Issues:
- I tried to find a better function for upserting a document, then a field or updating a value with no luck. Is there a function thats better suited for my needs? That would probably also adress the issue nr 2? The missing document is always created and the values seems to be updated with the newst ones. But the code always gives an error even it seems like its running seccessfully.