Model data being validated BEFORE the 'Before Save' operational hook called on an embedsMany relation
Bug/Feature request
We have 2 models related via an embedsMany relation such that: ParentModel.json
{
"name": "ParentModel",
"base": "PersistedModel",
"relations": {
"childModels":{
"model": "ChildModel",
"type": "embedsMany"
}
}
ChildModel.json
{
"name": "ChildModel",
"base": "Model",
"properties": {
"prop1":{
"type": "string",
"required": true
}
}
}
We would like to populate the value of prop1 in the ChildModel's before save hook...
ChildModel.observe('before save', (ctx, next)=>{
ctx.data.prop1 = 'some data';
next();
});
... however Loopback is throwing an exception before the before save hook is being called: The 'ParentModel' instance is not valid. Details: '_childModels' contains invalid item: <child model ID> (prop1 can't be blank)...
What we have observed is the following flow of data:
before savecalled on ParentModel- Data validated for ParentModel and all ChildModels
before savecalled on ChildModel
The documentation states that the before save hook is called before model validation, but this does not seem to be the case.
This leaves us with 2 options:
- Make the property not required
- Leave the property required and add the missing data using the ctx.currentInstance in the Parent Model's
before savehook, which is discouraged in loopback documentation
Expected result
The validation of ChildModel's properties should be executing AFTER the ChildModel's before save hook.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
This issue has been closed due to continued inactivity. Thank you for your understanding. If you believe this to be in error, please contact one of the code owners, listed in the CODEOWNERS file at the top-level of this repository.