0

I have a form were I can register a user with one or more addresses. To simplify things, I am sending to loopback:

{
  "id": 0,
  "name": "User Name",
  "addresses": [
    {
      "street": "xx",
      "city": "xx",
      "country": "xx"
    },
    {
      "street": "yy",
      "city": "yy",
      "country": "yy"
    }
  ]
}

On my User model I defined (I have an Address model too):

export class User extends Entity {
  @property({
    type: 'number',
    id: true,
    required: true,
  })
  id: number;

@property({
    type: 'string',
    required: true,
  })
  name: string;

 @hasMany(() => Address, {keyTo: ‘user_id’})
  Addresses: Array<Address>;
}

Also in UserRepository I has defined:

this.addresses = this.createHasManyRepositoryFactoryFor(
      'addresses',
      AddressRepositoryGetter,
    );

When I post the json, loopback throws the following error:

{
  "error": {
    "statusCode": 422,
    "name": "ValidationError",
    "message": "The `user` instance is not valid. Details: `addresses` is not defined in the model (value: undefined).",
    "details": {
      "context": "user",
      "codes": {
        "addresses": [
          "unknown-property"
        ]
      },
      "messages": {
        "addresses": [
          "is not defined in the model"
        ]
      }
    }
  }
}

My guess is that "addresses" relation is not being considered a property of the model. How can I solve this?. I know I have the option to do a separate request to save the addresses, but I want to avoid that.

artem
  • 46,476
  • 8
  • 74
  • 78
Eduardo
  • 1,781
  • 3
  • 26
  • 61

1 Answers1

1

This error is actually thrown by datasource juggler which is the underlying connector library for connecting with database. It seems addresses column is not defined your database in the User table. Please check that.

Samarpan
  • 913
  • 5
  • 12
  • Thanks, yes that was it. How can I send related data in the same request? Addresses is an array which will be handled in addresses model – Eduardo Mar 29 '19 at 12:58
  • Just the same way you are sending already. You just need to make sure that database have this column. However, juggler sometimes behave strangely. So I prefer handling of related data separately on my own in the controller in such cases. Related data is sent as is in the same request, but handled separately within controller. Try that if juggler doesn't create your related models on its own. – Samarpan Apr 01 '19 at 07:53
  • I will send related data separately to be handled in the controller. Thanks for the advice. – Eduardo Apr 05 '19 at 15:13