You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have ModelA that hasMany ModelB elements, how do I insert a new modelA with the associations already there for modelB? Or how do I associate the new record with the records of ModelB after the first one is saved?
It's not documented properly, but it's there. Whenever you do an association, accessors such as get, set, has, and del are added.
varPerson=db.define('person',{name : String});varAnimal=db.define('animal',{name : String});Animal.hasOne("owner",Person);// assumes column 'owner_id' in 'animal' table// get animal with id = 123Animal.get(123,function(err,Foo){// Foo has getOwner(), setOwner(), hasOwner(), etc.});
You can check the source here; usage in the test files here.
There's no option to create several instances of different models in one call, but you can create the instances manually and when you call .save() on the top one it should propagate.
varPerson=db.define('person',{name : String});varAnimal=db.define('animal',{name : String});Animal.hasOne("owner",Person);// ...varJohn=newPerson({name: "John"});varDeco=newAnimal({name: "Deco"});Deco.setOwner(John,function(){// John should be saved (to fetch it's ID) and also Deco should be saved});
varJohn=newPerson({name: "John",surname: "Doe",pets: [newPet({name: "Deco"}), ... ]});John.save(function(err){// assuming Person.hasMany("pets", Pet), Deco should be saved, so as John});
Activity
rainulf commentedon May 17, 2013
It's not documented properly, but it's there. Whenever you do an association, accessors such as get, set, has, and del are added.
You can check the source here; usage in the test files here.
dxg commentedon May 19, 2013
I'm starting to think we need a wiki..
gaudecker commentedon May 21, 2013
Did I misunderstand the original question? Is there a way to set the associations when calling
createon a model?Of course the example given by @rainulf gave works, but I think it'd be much cleaner this way.
dresende commentedon May 24, 2013
There's no option to create several instances of different models in one call, but you can create the instances manually and when you call
.save()on the top one it should propagate.dresende commentedon May 31, 2013
I'm going to try this in a couple of minutes. If I'm successful I'll post an example.
Adds initial code to support passing associations when creating new i…
dresende commentedon Jun 2, 2013
You should now be able to do something like:
ptnplanet commentedon Jun 2, 2013
Awesome!
dresende commentedon Jun 4, 2013
I'm going to close this for now. I'll add some tests a few tiny tweaks in the meantime.