brikteknologier / seraph-model

thin model layer for seraph/neo4j (node.js)
MIT License
111 stars 28 forks source link

beforeSave or Prepare don't modify the object #82

Closed tothsanka closed 9 years ago

tothsanka commented 9 years ago

Guys this lib is awesome, thanks for sharing it!

I tried to build UniqueID for each Node with a simple method, before I save them. Because I don't want to put this method-call before each .save() I tried to use beforeSave or prepare events.

This is what I have (obviously the uuid method is demonstration only) UserModel.schema = { uuid: {type: String, required: true}, name: {type: String, required: true}, };

UserModel.on('beforeSave', function (obj, callback) { if (typeof(obj.uuid) == 'undefined') { obj.uuid = parseInt(Math.random()*100000); } });

Unfortunately the object wont pickup uuid on beforeSave nor on prepare. So the validation stops ( Schema validation failed when parsing uuid = undefined )

Moreover I got uuid as primary key ( UserModel.setUniqueKey('uuid'); )

How should I do this? I understand if these events are read only, I'm just wondering if there is something out of the box.

Thanks

jonpacker commented 9 years ago

You're on the right track, you just need to call the callback :)

UserModel.on('prepare', function (obj, callback) {
  if (typeof(obj.uuid) == 'undefined') {
    obj.uuid = parseInt(Math.random()*100000);
  }
  callback(null, obj)
});

Good luck!

tothsanka commented 9 years ago

Great job! Thanks!

tothsanka commented 9 years ago

I just confirm the uuid is propagated properly to object level with the callback.

However I still get the "Schema validation failed when parsing uuid = undefined" if I set the uuid field required. I remove the required:true for now, because the field will be filled anyway.

Thanks

jonpacker commented 9 years ago

Yes, I believe the client side validation is performed before the prepare events are fired. If you set the uuid as your unique key, it will be automatically required by neo4j, and neo4j will refuse to save any user models without a uuid.

tothsanka commented 9 years ago

That's perfect!!