问题
How to prevent ArangoDB from throwing an exception during the Transaction when looking for a specific document which perhaps does not exist at that moment?
Nodejs sends the transaction in one block to ArangoDb where it gets processed. That's perfect. I want to unload all math to the server.
During the Transaction, I want to look at a specific Collection and check if a document exists, if document can be found, then get field 'balance', but if the Document cant be found or their field, then I dont want to throw an exception and dont want to stop the ongoing transaction. On the contrary, I much more want to proceed with the transaction, and we assign the variable oldBalance the string of '0'.
(for your information: there is a write lock for collection: 'user' specified on nodeJS side) and here you see part of transaction code sent to ArangoDB:
var db = require('internal').db;
// 1.) find specific document
var accountdoc = db.user.document('Johnny04'); // find doc by _key
this throws an exception if that Document with that particular _key cant be found. At that time the user probably has no entry in the collection. In that case we want to assume his balance to be string '0'. But unfortunately an exception was thrown already. I much more want to proceed like the following:
//2.) calculate newBalance = oldBalance + additional
if (accountdoc.error==true){ // document not found etc...
var oldBalance='0';
var documentExists = false;
} else {
var oldBalance=accountdoc.balance;
var documentExists = true;
var documentExistsID = accountdoc._id;
}
回答1:
Can't you handle the "document not found" error inside the transaction like this:
function (params) {
var db = require("org/arangodb").db;
var accountdoc;
// 1.) find specific document
try {
accountdoc = db.user.document('Johnny04'); // find doc by _key
}
catch (err) {
// document not found etc.
// TODO: rethrow exception if err is something different than "document not found"
}
// 2.) calculate newBalance = oldBalance + additional
if (accountdoc === undefined) { // document not found etc...
// create a new document with balance 0
db.user.save({ _key: 'Johnny04', balance: '0' }); // note: if this fails, the transaction will throw
}
else {
// update the existing document
var oldBalance = accountdoc.balance;
var newBalance = oldBalance + 42;
db.user.update('Johnny04', { balance: newBalance }); // note: if this fails, the transaction will throw
}
}
来源:https://stackoverflow.com/questions/23934058/arangodb-transactions-how-prevent-from-throwing-exceptions