As far as I can tell using Sequelizejs, it seems that there is no way to preserve associations of objects when the object itself is saved.
For example, I have a contact that can have 1 or more phone numbers. I currently have something like this for an association:
global.db.Contact.hasMany(global.db.PhoneNumber, {as: 'phoneNumbers'});
Using the vacation endpoint, I would like to publish a new contact object (with any provided phone numbers) and save it in the database. My request object looks something like this:
{ firstName: "john", lastName: "Doe", phoneNumbers: [ { number: "555-555-5555", type: "home" } ] }
Now I am passing this object to the assembly:
var contact = Contact.build(req.body);
And then call save (I know that I could use create instead of build / save, but we have user logic in save to track the changed data and which user made the modification)
contact.save();
This causes the following error, which makes sense.
column "phoneNumbers" of relation "Contacts" does not exist
A sql call attempts to set the value of the "phoneNumbers" column, which does not exist. Obviously, I do not want this to be done ... I really would like for each telephone number in the array to be created in bulk with the identifier of the contact I am creating.
The only example I found was the following: https://gist.github.com/sdepold/3040391 , and I really do not want to do this ... Since I am starting from the resting point, I would like to do this operation in general (I will have many models with associations). I will also need to do these operations in bulk (to import contacts from other sources), so I would prefer that this be the minimum number of sql calls. Has anyone found a good way to do this?
Nova706
source share