简体   繁体   中英

How to get inserted document's id in transaction? (arangoDB)

I've been searching the web a lot for clues but can't seem to find any...

public function createNew($name, $type, $restriction,$picture){
   global $connection;
   $trans=new Transaction($connection,array( 'collections' => array( 'write' => array( 'group_relations','groups' ),'read'=> array( 'group_relations','groups' ) ), 'waitForSync' => true ));
   $trans->setAction('function(){
      var db= require("@arangodb").db;
      var arr=db.groups.insert({"name":"'.$name.'","type":"'.$type.'","restriction":"'.$restriction.'","picture":"'.$picture.'"}).toArray();
                db.group_relations.insert({"_from":"users/'.$_SESSION['uid'].'","_to":"groups/"+arr[0]["_id"],"status":"admin"});
      }');
   $trans->execute();
}

this is a PHP function that makes a transaction. In the transaction, I'm trying to create a group, get its id and insert it in the relation collection between the creator and the new group.

Basically make the creator of the group the admin.

" : Uncaught triagens\\ArangoDb\\ServerException: 17 db.groups.insert(...).toArray is not a function". :未被捕获的triagens \\ ArangoDb \\ ServerException:17 db.groups.insert(...)。toArray不是函数”。

Any solutions?

The result of insert({...}) is always an object. The result of insert([{...},{...},...,{...}]) is always an array. In either case .toArray() does not help.

So if you'd like to make sure, that you have an array as a result type, please use the array insert also for single entries:

var arr=db.groups.insert(
  [{"name":"'.$name.'",
    "type":"'.$type.'",
    "restriction":"'.$restriction.'",
    "picture":"'.$picture.'"}]);

So in order to get back the ids from your inserts only:

var ids = []; 
db.groups.insert([{...},...,{...}]).forEach(
  function(obj) {ids.push(obj._id)});
...

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