Pre save hook with data from different schemas

Hi :smiley: I am working on my project where some of their models are: Portfolios, Charities and Causes. Portfolio has a charities_id field which stores the charities_id corresponding to that portfolio which are related to the charities model and an empty causes field. On the other hand, inside the charities model there is the causes field, which contains the id of the causes (related to the Causes model). Below you can see the schemas:

Portfolio schema:

Charities schema:

What I would like to achieve is to create a pre save hook in Portfolio, so that when adding a new portfolio, it takes the charities_id that are added to that portfolio, look for them in the charities model and add in portfolio->causes the causes_id that are in charities->causes.

Is this possible?

I appreciate any help,
Thanks!

Hi @usr1vang :wave: I think you can override the portfolios creation route.
Please take a look a this documentation

You can do something like this:

router.post('/portfolios', () => {
// get the data from req.body.data
// extract charities_id
// find charities
// extract causes from charities
// create the record
// serialize it
// send it
});

Let me know if you need more help on some points.

Hi, thanks for your replay.
I wrote the code attached below, where I add to portfolio->causes the charities->causes as I wanted. I would be missing the part of serialize and post it, is not clear to me how to do it, could you help me with some code?

My other doubt is if I have to remove at the beginning of the route the:
permissionMiddlewareCreator.create(),

I keep waiting your comments,
Thanks.

My other doubt is if I have to remove at the beginning of the route the:
permissionMiddlewareCreator.create(),

You must keep this for security purpose.

Does your code working? I think it should work like this.

I would be missing the part of serialize and post it, is not clear to me how to do it, could you help me with some code?

This part is useful if you don’t use next(), if it work like that ignore these steps.

1 Like