Monday, 5 June 2017

JSON serialization of Many to One associations on model create/update

I want to build a single API that can create or update a model along with it's many to one relation ship. Several Pets can have the same user as their owner. Pet cannot have multiple owners.

So my User.js has an association like this:

// Reference to pets for this user
descriptors: {
  collection: 'permissiondescriptor',
  via: 'owner'
}

And my Pet.js has a non unique foreign key association like this:

// The owner to which this pet belongs to
owner: {
  model: 'user'
}

I have a createOrUpdate in my User as well as Pet model. I first createOrUpdate my user instance and then I createOrUpdate my pets. Once the pets have been created or updated, I try to update the parent user with the updated pets doing a _.merge(userInstance, {pets: updatedPets}) with the intent to use this in the overridden .toJSON of the User.js to return the user along with their pets as json.

However the below piece of code does not work as expected

// User.js
toJSON: function () {
  let self = this.toObject(),
    // The self.pets here is undefined despite me explicitly setting .pets on this user instance right before the JSON serialization
    result = {pets: self.pets};
  return result;
}

However if I use a name different from the one to many associations name i.e _.merge(userInstance, {updatedPets: updatedPets}) instead of _.merge(userInstance, {pets: updatedPets}), I am able to access self.updatedPets correctly in my .toJSON.

When I do a User.find with populate('pets') the pets are correctly populated. So I end up with code in my .toJSON that has to handle whether the pets were createdOrUpdated or just came from a read only operation using something like result = {pets: self.pets || self.updatedPets};



via Pratik Mandrekar

No comments:

Post a Comment