Skip to content

Document using "this" instead of "data" args in beforeValidate model hook #1036

@aantipov

Description

@aantipov

Hi,
I use loopback version 2.10.2.
I have a model with a base "PersistedModel" and defined some properties on it.

{
  "name": "Hike",
  "base": "PersistedModel",
  "idInjection": true,
  "properties": {
    "title": {
      "type": "string",
      "required": true
    },
    "desc": {
      "type": "string"
    },
    "created": {
      "type": "date",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "author": {
      "type": "belongsTo",
      "model": "Account",
      "foreignKey": "authorId"
    }
  },
  "acls": [],
  "methods": []
}

Note that property created is required.

Then in model hook I try to set created value before validation:

Hike.beforeValidate = function (next, data) {
    data.created = new Date();
    next();
  };

After this I try to save a new object without created property & get validation error:

{
  "error": {
    "name": "ValidationError",
    "status": 422,
    "message": "The `Hike` instance is not valid. Details: `created` can't be blank (value: undefined).",
    "statusCode": 422,
    "details": {
      "context": "Hike",
      "codes": {
        "created": [
          "presence"
        ]
      },
      "messages": {
        "created": [
          "can't be blank"
        ]
      }
    },
    "stack": "ValidationError: The `Hike` instance is not valid. Details: `created` can't be blank (value: undefined)..."
  }
}

Here is a screenshot from api explorer with a post operation http://take.ms/iQdeV

Why was my model not actually changed before validation?

Metadata

Metadata

Assignees

Labels

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions