loopback icon indicating copy to clipboard operation
loopback copied to clipboard

Model data being validated BEFORE the 'Before Save' operational hook called on an embedsMany relation

Open frankorama opened this issue 9 years ago • 2 comments

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:

  1. before save called on ParentModel
  2. Data validated for ParentModel and all ChildModels
  3. before save called 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:

  1. Make the property not required
  2. Leave the property required and add the missing data using the ctx.currentInstance in the Parent Model's before save hook, which is discouraged in loopback documentation

Expected result

The validation of ChildModel's properties should be executing AFTER the ChildModel's before save hook.

frankorama avatar Feb 02 '17 21:02 frankorama

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.

stale[bot] avatar Aug 23 '17 15:08 stale[bot]

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.

stale[bot] avatar Sep 06 '17 15:09 stale[bot]