How do I access inserted document's _id within a transaction in ArangoDB

182 views Asked by At

I don't see any examples of accessing inserted/updated documents key's when in a transaction.

var collections = {write: ['foo','bar']};
var action = String(function () {
    var doc = params['doc'];
    var relatedDoc = params['relatedDoc'];
    var db = require('internal').db;
    db.foo.save(doc); // how do I access the _id, key etc of the newly inserted doc?
    relatedDoc.foos.push(doc._id); // _id does not exist yet
    db.bar.save(relatedDoc);
    return {success: true};
});
var params = {
    doc: doc,
    relatedDoc: relatedDoc
};
db.transaction(collections, action, params, function (err, result) {
    if (err) {
        return dfd.reject(err);
    }
    return dfd.resolve(result);
});
1

There are 1 answers

0
stj On BEST ANSWER

The collection.save() method will return some meta-data for the saved document:

  • _rev: document revision id (auto-generated by the server)
  • _key: document key (either specified by user in _key attribute or auto-generated by the server if not)
  • _id: same as key, but also including collection name

To use the generated id in your code, you can capture the result of collection.save() in a variable and use it as follows:

var collections = {write: ['foo','bar']};
var action = String(function () {
    var doc = params['doc'];
    var relatedDoc = params['relatedDoc'];
    var db = require('internal').db;
    var newDoc = db.foo.save(doc);     // capture result of save in newDoc
    relatedDoc.foos.push(newDoc._id);  // use newDoc._id for 
    db.bar.save(relatedDoc);
    return {success: true};
});
var params = {
    doc: doc,
    relatedDoc: relatedDoc
};
db.transaction(collections, action, params, function (err, result) {  
  if (err) {
      return dfd.reject(err);
    }
    return dfd.resolve(result);
});