brikteknologier / seraph-model

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

findOrCreate function ? #109

Closed shanmarkus closed 8 years ago

shanmarkus commented 8 years ago

Hi,

Just asking, is there any method for saving a model which checking if it exist in the db or not. Currently, i'm using model.where and model.save to achieve this.

Thank you for your help.

jonpacker commented 8 years ago

Hey! I think the best way to achieve this is to use setUniqueKey. For example, if you do this:

User.setUniqueKey('name', true);
User.save({name: 'Jon', country: 'Norway'}, (e, node) => console.log(node))
// -> { name: 'Jon', country: 'Norway', id: 1 }
User.save({name: 'Jon', country: 'Norway'}, (e, node) => console.log(node))
// -> { name: 'Jon', country: 'Norway', id: 1 }

However, this only checks that key, not the whole object. Doing a save would update the object with the existing matching key to update its properties to whatever you sent, instead of returning the old ones.

User.save({name: 'Jon', country: 'Australia'}, (e, node) => console.log(node))
// -> { name: 'Jon', country: 'Australia', id: 1 }
// same node, same id, but "country" has been changed to "Australia".

Does this help? Otherwise, I suggest sticking to using where and find together, that's all that a findOrCreate function would be if it was added.