简体   繁体   中英

Hyperledger Composer: How to push array of assets into another asset's field?

I'm trying to re-create one of my chaincode written in GoLang in Composer. Model.cto

asset Carton identified by cartonId {
o String cartonId
o String manufacturerId
o String dateOfDeparture optional
o String recipient optional 
o String currentOwner
o String status
--> Unit[] units optional
o Trackrecord[] trackrecord optional 
}
 transaction MakeCarton {
 --> Unit[] unit
 o String Id
 }
 asset Unit identified by unitId {
 o String unitId
 o String cartonId
 o String manufacturerId
 o String dateOfDeparture
 o String recipient
 o Trackrecord[] trackrecord
 o String currentOwner
 o String status  
  }

So I need to create transaction which creates one carton and accepts array of units and the cartonId.

  function makeCarton(make) {
  var carton =  getFactory().newResource('org.acme.mynetwork','Carton',make.Id);
  //carton.cartonId = make.Id ;
  var unitobjs = new Array() ;
  for(var i=0; i < make.unit.length ; i++) {
  var unitobj =  getFactory().newResource('org.acme.mynetwork','Unit',make.unit[i].unitId) ;                                          
  unitobj = getFactory().newRelationship('org.acme.mynetwork','Unit',make.unit[i].unitId) ;
  unitobjs.push(unitobj) ;
   }
  for(var i = 0 ; i< make.unit.length ; i++) {
  carton.units.push(make.unit[i]) ;
  }
  // getFactory().newRelationship('org.acme.mynetwork','Unit',make.unit[i].unitId)
  carton.manufacturerId= make.unit.manufacturerId ;
  carton.currentOwner = make.unit.currentOwner ;
  carton.status = 'At '+ make.unit.currentOwner ;
  return getAssetRegistry('org.acme.mynetwork.Carton').then(function (assetRegistry) {
        return assetRegistry.add(carton);
    });
    }

Submitting this transaction generates an Error: carton.units undefined

You don't initialise carton.units . You can just copy the array, using:

carton.units = make.unit;

That said, I don't really understand your model -- a carton has an array of units, and each unit has an owner, but then a carton also has an owner.

I had the same issue. And this post helped me solve it. However, for me,

 transaction MakeCarton {
   --> Unit[] unit
   o String Id
 }

had to be changed to

 transaction MakeCarton {
   o Unit[] unit
   o String Id
 }

Otherwise there was below error:

Unhandled error for request POST /api/MakeCarton: Error: Invalid JSON data. Found a value that is not a string: [object Object],[object Object] for relationship RelationshipDeclaration {name=unit, type=org.acme.mynetwork.Unit, array=true, optional=true} at JSONPopulator.visitRelationshipDeclaration (/usr/local/lib/node_modules/composer-rest-server/node_modules/composer-common/lib/serializer/jsonpopulator.js:264:31)

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