简体   繁体   中英

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

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);
});

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM